spring计划任务
配置开启计划任务支持
开启计划任务支持@EnableScheduling
package com.sky.springtest.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@ComponentScan({"com.sky.springtest"})
@EnableScheduling
public class TaskSchedulerConfig {}
计划任务类
spring通过@Scheduled
支持多种类型的计划任务
- fixedRate:固定时间间隔执行
- fixedDelay:执行完当前任务后,推迟一个时间段再次执行
- initialDelay:第一次延迟多长时间后再执行
- cron :
该参数接收一个cron表达式,cron表达式是一个字符串,字符串以5或6个空格隔开,分开共6或7个域,每一个域代表一个含义。
cron表达式语法
[秒] [分] [小时] [日] [月] [周] [年]
package com.sky.springtest.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduledTaskService {
@Scheduled(fixedRate = 5000)
public void testFixedRate5s() {
System.err.println("间隔5s执行一次" + System.currentTimeMillis());
}
@Scheduled(cron = "0 1 12 ? * *")
public void testFixTimeExecution() {
System.err.println("每天12点1分:指定时间执行=" + System.currentTimeMillis());
}
}
测试类
package com.sky.springtest.config;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TaskSchedulerConfigTest {
private static AnnotationConfigApplicationContext context = null;
@BeforeClass
public static void beforeClass() {
context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);
}
@Test
public void test() {
// 防止主进程立即运行完毕
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
}
context.close();
}
}
/*测试结果:
间隔5s执行一次1564925649293
间隔5s执行一次1564925654295
间隔5s执行一次1564925659295
延迟10s,间隔5s执行一次1564925659295
间隔5s执行一次1564925664294
延迟10s,间隔5s执行一次1564925664294
间隔5s执行一次1564925669295
延迟10s,间隔5s执行一次1564925669295
*/