When I was doing enterprise development recently, there was a requirement for me to adjust and optimize the scheduled tasks for sending emails.

@Scheduled tasks

The scheduled task of sending emails that has been completed looks like this:

1
2
3
4
5
6
7
8
9
10
@Component
public class EmailScheduled{

@Scheduled(cron = "0 0 23 * * * ?")
public void emailSend(){
...

}
}

The difficulty of optimization and adjustment lies in the trouble of debugging:

  • The code of the current development environment does not set a unified interface to debug back-end timing tasks through the front-end
  • If you debug by modifying cron, you need to restart the project, and more importantly, you will send a lot of harassing emails
  • Another idea is to call the method in the test code, but it is also very tricky

In fact, there is a relatively simple idea, rewriting the afterPropertiesSet method of the InitialzingBean class.

When spring initializes a bean, if the bean implements the InitializingBean interface, it will automatically call the afterPropertiesSet method, so it is conceivable that in this way, you can debug by restarting idea:

1
2
3
4
5
6
7
8
9
10
11
12
13
@Component
public class EmailScheduled implements InitializingBean{

@Scheduled(cron = "0 0 23 * * * ?")
public void emailSend(){
...
}

@Override
public void afterPropertiesSet() throws Exception{
emailSend();
}
}

Is not it simple? Of course, this may not be the optimal solution, but if it is only used briefly in the project, it is not a big problem.