【轉(zhuǎn)載請注明出處】:http://www.itdecent.cn/p/fe257adc331d
如果不用集群方式,不用將任務持久化,只是單節(jié)點單純的實現(xiàn)定時任務的話,這種方式無疑是最快的一種,從構(gòu)建項目到定時任務跑起來不會超過10分鐘。
官方的demo:
git clone https://github.com/spring-guides/gs-scheduling-tasks.git
1、啟用定時任務
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class);
}
}
加上@EnableScheduling即可開啟定時任務。
2、線程池配置
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(20));
}
}
3、編寫定時任務類
@Component
public class ScheduledTasks {
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}
}
在定時任務類上加上注解@Component,在執(zhí)行方法上加上注釋@Scheduled即可啟動該定時任務。
4、@Scheduled參數(shù):
4.1 fixedRate
Execute the annotated method with a fixed period in milliseconds between invocations.
fixedRate 是兩次任務的開始點的差值毫秒數(shù),如:
@Scheduled(fixedRate=1000):從第一次開始執(zhí)行的時間點算起,每隔1秒就會執(zhí)行一次
4.2 fixedDelay
Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.
fixedDelay 是上次任務結(jié)束的時間點與下次任務的開始時間點的差值毫秒數(shù),如:
@Scheduled(fixedDelay=1000):上一次任務執(zhí)行完成后等待1秒再執(zhí)行下次任務
4.3 cron
@Scheduled(cron="..."):按cron規(guī)則執(zhí)行,例如:
"0 0 * * * " 每個小時的0分0秒
"/10 * * * * *" 每10秒鐘
"0 0 8-10 * * *" 每天整8點、9點、10點
"0 0 6,19 * * *" 每天6點和19點整點
"0 0/30 8-10 * * *" 每天8:00, 8:30, 9:00, 9:30, 10:00 和 10:30
"0 0 9-17 * * MON-FRI" 周一到周五每天9點至17點之間的每個整點
"0 0 0 25 12 ?" 每個圣誕節(jié)午夜時分
5、多節(jié)點改造
上面只是介紹了單節(jié)點的實現(xiàn)方式,現(xiàn)在系統(tǒng)基本都是多節(jié)點部署的,也是為了防止單節(jié)點故障,基于當前單節(jié)點的實現(xiàn)方式,改造成多節(jié)點也比較簡單??梢杂梅植际芥i解決這個問題,在定時任務開始執(zhí)行的時候先獲取鎖,只有獲取成功的節(jié)點執(zhí)行定時任務,沒獲取到鎖的不執(zhí)行。關(guān)于分布式鎖在后面的文章中會單獨講解,這里就不介紹了。
【轉(zhuǎn)載請注明出處】:http://www.itdecent.cn/p/fe257adc331d
