Spring scheduled tasks
There are three main annotations for scheduled tasks:
// 1.主要用于标记配置类,兼备Component的效果。
@Configuration
// 2.开启定时任务。
@EnableScheduling
// 3. 放在作为定时任务的方法上,标识为定时任务。
@Scheduled
code example
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration // 1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class TestJob {
Log log = LogFactory.getLog(getClass());
// 容器启动后,延迟60秒后再执行一次定时器,以后每60秒再执行一次该定时器。
@Scheduled(initialDelay = 60 * 1000, fixedRate = 60 * 1000)
public void doWork() {
log.info("定时任务:执行");
}
}
Two ways to set up scheduled tasks
Set directly in the code (hardcoded, not recommended)
As in the above code, use initialDelay and fixedRate to set the time directly.
Read Cron expressions from configuration files (recommended)
Timing task code
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration // 1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class TestJob {
Log log = LogFactory.getLog(getClass());
// 定时器触发时间的cron,从配置文件 properties/yaml 中读取。
@Scheduled(cron = "${test.job.cron}")
public void doWork() {
log.info("定时任务:执行");
}
}
Corresponding application.properties
configuration:
# TestJob定时任务的cron表达式:每隔1分钟执行一次。
test.job.cron=0 * * * * *
cron expression
Execute every 1 minute (whole minute)
test.job.cron=0 * * * * *
Execute every 5 minutes (whole minutes)
0 */5 * * * *