Global timing task-CronUtil
Introduction
CronUtil realizes unified timing task scheduling through a global timing task configuration file.
use
1. Configuration file
For Maven project, at first src/main/resources/config
placed under cron.setting file (this is the default path of the file), and then placed in the file timing rules, rules are as follows:
# 我是注释
[com.company.aaa.job]
TestJob.run = */10 * * * *
TestJob2.run = */10 * * * *
Brackets indicate grouping, and also indicate the name of the package where the class or object method needs to be executed. This type of writing is helpful to distinguish the timing tasks of different services.
TestJob.run
Indicates the name of the class and method that need to be executed (invoked by reflection, dependency injection of Spring and any framework is not supported), and the */10 * * * *
expression of a timed task. Here, it is executed every 10 minutes. The above configuration is equivalent to:
com.company.aaa.job.TestJob.run = */10 * * * *
com.company.aaa.job.TestJob2.run = */10 * * * *
For tips about expression syntax, see: http://www.cnblogs.com/peida/archive/2013/01/08/2850483.html
2. Start
CronUtil.start();
If you want the execution of the job to end at the same time as the timing task thread, you can set the timing task as a daemon thread. It should be noted that in this mode, all job threads will be terminated immediately when stop is called. Please make sure that your job can be interrupted:
//使用deamon模式,
CronUtil.start(true);
3. Close
CronUtil.stop();
more options
Second match and year match
Taking into account the compatibility of Quartz expressions and the need for second-level precision matching, Hutool can be compatible by setting the second matching mode.
//支持秒级别定时任务
CronUtil.setMatchSecond(true);
At this time, Hutool is compatible with Quartz expressions (5-digit expressions and 6-digit expressions are compatible)
Dynamically add timed tasks
Of course, if you want to dynamically add timed tasks, just use the CronUtil.schedule(String schedulingPattern, Runnable task)
method (the timed 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.");
}
});
// 支持秒级别定时任务
CronUtil.setMatchSecond(true);
CronUtil.start();