當前位置:編程學習大全網 - 源碼下載 - SpringBoot幾種定時任務的實現方式

SpringBoot幾種定時任務的實現方式

第壹種比較簡單

第二種

@SpringBootApplication

/*

*? 開啟對定時任務的支持

*? 在相應的方法上添加@Scheduled聲明需要執行的定時任務。

*/

@EnableScheduling

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class, args);

}

}

@SpringBootApplication

/*

*? 開啟對定時任務的支持

*? 在相應的方法上添加@Scheduled聲明需要執行的定時任務。

*/

@EnableScheduling

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class, args);

}

}

/*把普通pojo實例化到spring容器中,相當於配置文件中的

<bean id="" class=""/>

若想動態改變其值需要繼承SchedulingConfigurer

*/

public class AutoSchedule? implements? SchedulingConfigurer{

private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

private static final String DEFAULT_CRON = "0/5 * * * * ?";

private String cron = DEFAULT_CRON;

@Override

public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

//? ?Runnable(線程接口類) 和CronTrigger(定時任務觸發器)

taskRegistrar.addTriggerTask(() -> {

// 定時任務的業務邏輯

System.out.println("動態修改定時任務cron參數,當前時間:" + dateFormat.format(new Date()));

}, (triggerContext) -> {

// 定時任務觸發,可修改定時任務的執行周期

CronTrigger trigger = new CronTrigger(cron);

Date nextExecDate = trigger.nextExecutionTime(triggerContext);

return nextExecDate;

});

}

public void setCron(String cron) {

System.out.println("當前cron="+this.cron+"->將被改變為:"+cron);

this.cron = cron;

}

}

第三種

@RestController

@Component

public class CrudSchelud? {

//用threadPoolTaskScheduler 類實現對任務的定時調度功能,

//重寫CronTrigger觸發器,任務卻被不斷調用3

@Autowired

private ThreadPoolTaskScheduler threadPoolTaskScheduler;

private ScheduledFuture<?> future;

@Bean

public ThreadPoolTaskScheduler threadPoolTaskScheduler() {

return new ThreadPoolTaskScheduler();

}

@RequestMapping("/startCron")

public String startCron() {

future = threadPoolTaskScheduler.schedule(new MyRunnable(), new CronTrigger("0/5 * * * * *"));

System.out.println("DynamicTask.startCron()");

return "startCron";

}

@RequestMapping("/stopCron")

public String stopCron() {

if (future != null) {

future.cancel(true);

}

System.out.println("DynamicTask.stopCron()");

return "stopCron";

}

@RequestMapping("/changeCron10")

public String startCron10() {

stopCron();// 先停止,在開啟.

future = threadPoolTaskScheduler.schedule(new MyRunnable(), new CronTrigger("*/10 * * * * *"));

System.out.println("DynamicTask.startCron10()");

return "changeCron10";

}

private class MyRunnable implements Runnable {

@Override

public void run() {

System.out.println("DynamicTask.MyRunnable.run()," + new Date());

}

}

}

  • 上一篇:2022幽默坑人的口令紅包句子
  • 下一篇:壹個困擾我這個高級程序員的挺牛的病毒或叫木馬,達人請進!
  • copyright 2024編程學習大全網