/**
* @ Author zhangsf
* @CreateTime 2019/5/1 - 5:44 PM
*/
package com.zsf.spider.controller;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import static com.zsf.spider.util.DateUtil.now;
@Configuration
@EnableScheduling // 1.开启定时任务
@EnableAsync // 2.开启多线程
public class MultithreadScheduleTask {
@Async
@Scheduled(fixedDelay = 1000) //间隔1秒或者使用cron = "0/1 * * * * ?"
public void first() throws InterruptedException {
System.out.println("第一个定时任务开始 : " +now() + "\r\n线程 : " + Thread.currentThread().getName());
System.out.println();
Thread.sleep(1000 * 10);
}
@Async
@Scheduled(fixedDelay = 2000)
public void second() {
System.out.println("第二个定时任务开始 : " + now() + "\r\n线程 : " + Thread.currentThread().getName());
System.out.println();
}
}
从控制台可以看出,第一个定时任务和第二个定时任务互不影响,分别间隔为1s和2s;
由于开启了多线程,第一个任务的执行时间也不受其本身执行时间的限制,所以需要注意可能会出现重复操作导致数据异常。