CronUtil
Introduction
CronUtil achieves unified scheduled task scheduling through a global configuration file for timed tasks.
Usage
1. Configuration File
For Maven projects, place the cron.setting file under src/main/resources/config
(this is the default path for this file), and then add the scheduling rules in the file, as follows:
# I am a comment
[com.company.aaa.job]
TestJob.run = */10 * * * *
TestJob2.run = */10 * * * *
The square brackets indicate a group and also represent the package name of the class or object method that needs to be executed. This writing method helps distinguish between scheduled tasks for different businesses.
TestJob.run
indicates the class name and method name that need to be executed (called through reflection, does not support dependency injection of Spring or any framework). */10 * * * *
indicates the scheduled task expression, which means to execute once every 10 minutes. The above configuration is equivalent to:
com.company.aaa.job.TestJob.run = */10 * * * *
com.company.aaa.job.TestJob2.run = */10 * * * *
Tip: For expression syntax, see: http://www.cnblogs.com/peida/archive/2013/01/08/2850483.html
2. Start Up
CronUtil.start();
If you want the executed job to end at the same time as the scheduled task thread, you can set the scheduled task as a daemon thread. Note that in this mode, all job threads will be immediately terminated when stop is called, so ensure that your job can be interrupted:
// Use deamon mode
CronUtil.start(true);
3. Shutdown
CronUtil.stop();
More Options
Second Matching and Year Matching
Considering the compatibility of Quartz expressions and the need for second-level precision matching, Hutool can be set to use second matching mode to achieve compatibility.
// Support second-level scheduled tasks
CronUtil.setMatchSecond(true);
At this time, Hutool can support Quartz expressions (both 5-digit and 6-digit expressions are compatible)
Dynamically Adding Scheduled Tasks
Of course, if you want to dynamically add scheduled tasks, use the CronUtil.schedule(String schedulingPattern, Runnable task)
method (scheduled tasks added using this method will not be written to the configuration file).
CronUtil.schedule("*/2 * * * * *", new Task() {
@Override
public void execute() {
Console.log("Task excuted.");
}
});