1、schedule 注解定時(shí)器
import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Date; /** * 注解 定時(shí)器 * */ @Component @Configuration @EnableScheduling public class FirstSecheduler {
//五秒 運(yùn)行一次 @Scheduled(cron = "0/5 * * * * ?") public void fiveSeconds(){
System.out.println("start:"+new Date().getSeconds()); System.out.println("你好啊"); System.out.println("end:"+new Date().getSeconds()); } } 2,、動(dòng)態(tài)定時(shí)器 可配置間隔時(shí)間 和內(nèi)容
/** * 實(shí)現(xiàn)sechedule */ @Component @Configuration @EnableScheduling public class SecondSchedule implements SchedulingConfigurer {
@Override public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.addTriggerTask(() ->System.out.println("執(zhí)行動(dòng)態(tài)定時(shí)任務(wù): " + new Date()), triggerContext -> { //2.1 從數(shù)據(jù)庫(kù)獲取執(zhí)行周期 String cron = "0/5 * * * * ?"; //2.3 返回執(zhí)行周期(Date) return new CronTrigger(cron).nextExecutionTime(triggerContext); }
); } } 3,、使用多線程定時(shí)器
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 org.springframework.stereotype.Component; import java.util.Date; /** * 多線程定時(shí)任務(wù) */
@Component @EnableScheduling //開啟定時(shí)器 @EnableAsync //開啟多線程 public class ThreeSChedule {
@Async @Scheduled(fixedDelay = 1000) public void first(){
System.out.println("first:"+new Date().toLocaleString()); }
@Async @Scheduled(fixedDelay = 1000) public void second(){
System.out.println("second:"+new Date().toLocaleString()); }
} 4,、使用外部 quartz定時(shí) pom配置
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.1</version> </dependency>
import java.util.Date; /** * 定義任務(wù)類 實(shí)現(xiàn) Job 接口 */ public class FirstQuartz implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("quartz"+new Date().toLocaleString());
} }
import org.quartz.*; import org.quartz.impl.StdSchedulerFactory;
/** * 主函數(shù)調(diào)用quartz */ public class QuartzMain {
public static void main(String[] args) throws Exception{
//創(chuàng)建job對(duì)象 JobDetail jobDetail = JobBuilder.newJob(FirstQuartz.class).build();
//觸發(fā)時(shí)間 Trigger trigger = TriggerBuilder.newTrigger().withSchedule( CronScheduleBuilder.cronSchedule("0/2 * * * * ?")).build();
//作業(yè)內(nèi)容 Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.scheduleJob(jobDetail,trigger); //啟動(dòng) scheduler.start();
} }
可根據(jù)不同需求使用
以上是自學(xué)總結(jié),。有借鑒前輩帖子望見諒。不足之處請(qǐng)多多指教
|