SpringBoot定時任務簡單使用和自定義開啓關閉修改週期

一、簡單使用

1.pom加入基本springboot基本的starter即可

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>

2.@Scheduled 參數可以接受兩種定時的設置,一種是我們常用的cron="*/6 * * * * ?",一種是 fixedRate = 6000,兩種都表示每隔六秒打印一下內容。

fixedRate 說明

  • @Scheduled(fixedRate = 6000) :上一次開始執行時間點之後6秒再執行

  • @Scheduled(fixedDelay = 6000) :上一次執行完畢時間點之後6秒再執行

  • @Scheduled(initialDelay=1000, fixedRate=6000) :第一次延遲1秒後執行,之後按fixedRate的規則每6秒執行一次

@Component
public class TimingTask {
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");    
    @Scheduled(cron="*/6 * * * * ?")    
    private void process(){
    System.out.println("this is scheduler task runing  "+new Date());
    }
    @Scheduled(fixedRate = 6000)
    public void reportCurrentTime() {
        System.out.println("現在時間:" + dateFormat.format(new Date()));
    }
}

3.啓動類加上@EnableScheduling註解。

@SpringBootApplication(exclude = MongoAutoConfiguration.class)
@EnableScheduling
public class DemoApplication {
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}

4.運行結果

this is scheduler task runing  Thu Jul 18 10:59:06 CST 2019
現在時間:10:59:10
this is scheduler task runing  Thu Jul 18 10:59:12 CST 2019
現在時間:10:59:16
this is scheduler task runing  Thu Jul 18 10:59:18 CST 2019
現在時間:10:59:22
this is scheduler task runing  Thu Jul 18 10:59:24 CST 2019
現在時間:10:59:28

以上就是定時任務的簡單使用。但是有時候,定時任務需要關閉,和開啓,或者修改定時任務的運行週期,可以使用下面的方式實現.

二、高級使用,自定義定時任務,關閉,開啓,修改週期

1.說明

  • ThreadPoolTaskScheduler:線程池任務調度類,能夠開啓線程池進行任務調度。
  • ThreadPoolTaskScheduler.schedule()方法會創建一個定時計劃ScheduledFuture,在這個方法需要添加兩個參數,Runnable(線程接口類) 和CronTrigger(定時任務觸發器)
  • 在ScheduledFuture中有一個cancel可以停止定時任務。
@RestController
@RequestMapping("/time")
public class DynamicScheduledTask {
	private static String DEFAULT_CRON = "0/5 * * * * ?";
	@Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    private ScheduledFuture<?> future;
    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
       return new ThreadPoolTaskScheduler();
    }
    @RequestMapping("/{id}/startCron")
    public String startCron(@PathVariable("id") String id) {
       future = threadPoolTaskScheduler.schedule(new MyRunnable(), new CronTrigger(DEFAULT_CRON));
       System.out.println("DynamicTask.startCron()"+"------"+id);
       return "startCron";
    }
    @RequestMapping("/{id}/stopCron")
    public String stopCron(@PathVariable("id") String id) {
       if (future != null) {
           future.cancel(true);
       }
       System.out.println("DynamicTask.stopCron()"+"------"+id);
       return "stopCron";
    }
    @RequestMapping("/{id}/changeCron10")
    public String startCron10(@PathVariable("id") String id) {
       stopCron(id);// 先停止,在開啓.
       future = threadPoolTaskScheduler.schedule(new MyRunnable(), new CronTrigger("*/10 * * * * *"));
       System.out.println("DynamicTask.startCron10()"+"------"+id);
       return "changeCron10";
    }
    private class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("DynamicTask.MyRunnable.run()," + new Date());
        }
     }
}

如果想,做成後臺管理,添加刪除定時任務,可以將定時任務,持久化到數據庫,自定義開發MyRunnable定時任務的業務類,也持久化到數據庫,然後,threadPoolTaskScheduler.schedule要的業務類,可通過反射實例化出來,傳遞,然後,通過url,id參數,來開啓,關閉,刪除,對應的定時任務。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章