生活随笔
收集整理的這篇文章主要介紹了
【+定时任务】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用spring task 框架設置定時任務
首先,創建一個springboot的工程,不用做任何配置;
然后,在啟動類里寫如下代碼
package com.cc.schedu;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;import java.text.DateFormat;
import java.util.Date;@EnableScheduling
@SpringBootApplication
public class ScheduApplication {public static void main(String[] args
) {SpringApplication.run(ScheduApplication.class, args
);}@Scheduled(fixedRate
=30*1000 )public void playsth(){System.out
.println("提醒女生吃藥..........."+ DateFormat.getDateInstance().format(new Date()));}@Scheduled(fixedRate
= 2*1000)public void playsth2(){System.out
.println("提醒女生多喝熱水.........."+ DateFormat.getDateInstance().format(new Date()));}}
CRON表達式
在上面的代碼中,如何只在白天發送消息,而在晚上不發送消息;
使用的技術是cron表達式
@Scheduled(cron
="0 0/30 9=22 * * ?") @Scheduled(cron
="0 0 9=22/3 * * ?")
生成cron表達式的網站生成cron表達式的網站
下圖是9點到22點提醒女神吃藥并且每個三個小時提醒一次的表達式
其中,星期日為第一天,星期六為第七天
總結
以上是生活随笔為你收集整理的【+定时任务】的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。