在springboot中使用定時任務

1酌畜、使用注解方式

? 首先需要在啟動類下添加 @EnableScheduling 注解(@EnableAsync是開啟異步的注解)

package com.fongtech.cli;

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.scheduling.annotation.EnableAsync;

import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication

@MapperScan("com.fongtech.cli.mbg.*.**")

@EnableAsync

@EnableScheduling

public class SpringbootAdminApplication {

? ? public static void main(String[] args) {

? ? ? ? SpringApplication.run(SpringbootAdminApplication.class, args);

? ? }

}

? 接著在需要用到定時任務的類和方法下加 @Component 和 @Scheduled(cron = "0 0/1 * * * ? ")注解,其中@Scheduled()中的 ‘cron’ 有固定的格式。(@Async注解表示開啟異步)

@Slf4j

@Component

public class AsyncTaskConfiguration {

? ? /**

? ? * 每分鐘檢查任務列表织鲸,判斷任務類型執(zhí)行相應的任務

? ? * 根據實際任務執(zhí)行情況,限定執(zhí)行任務數量

? ? */

? ? @Scheduled(cron = "0 0/1 * * * ? ")

? ? @Async

? ? public void startCommonTask() throws Exception {

? ? ? ? log.info("startCommonTask? start........." + Thread.currentThread().getName());

? ? ? ? commonTaskService.startCommonTask();

? ? ? ? log.info("startCommonTask? end........." + Thread.currentThread().getName());

? ? }}

2棍丐、使用實現接口的方式

? 通過實現 SchedulingConfigurer 接口渠牲,可對定時任務進行操作。實現接口的方式相比使用注解更加靈活泌参,但需要編寫代碼脆淹,相對繁瑣。

? 實現工具類如下:

package com.fongtech.cli.admin.tasktime;

import com.fongtech.cli.common.util.BeanUtils;

import org.springframework.context.annotation.Configuration;

import org.springframework.scheduling.SchedulingException;

import org.springframework.scheduling.TaskScheduler;

import org.springframework.scheduling.annotation.EnableScheduling;

import org.springframework.scheduling.annotation.SchedulingConfigurer;

import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import org.springframework.scheduling.config.TriggerTask;

import org.springframework.scheduling.support.CronTrigger;

import javax.annotation.PostConstruct;

import java.util.Map;

import java.util.Set;

import java.util.concurrent.ConcurrentHashMap;

import java.util.concurrent.ScheduledFuture;

/**

* @author linb

* @date 2020/6/15 11:16

*/

@Configuration

//@EnableScheduling

public class DefaultSchedulingConfigurer implements SchedulingConfigurer {

? ? private ScheduledTaskRegistrar taskRegistrar;

? ? private Set<ScheduledFuture<?>> scheduledFutures = null;

? ? private Map<String, ScheduledFuture<?>> taskFutures = new ConcurrentHashMap<>();

? ? @Override

? ? public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

? ? ? ? this.taskRegistrar = taskRegistrar;

? ? }

? ? @SuppressWarnings("unchecked")

? ? private Set<ScheduledFuture<?>> getScheduledFutures() {

? ? ? ? if (scheduledFutures == null) {

? ? ? ? ? ? try {

? ? ? ? ? ? ? ? // spring版本不同選用不同字段scheduledFutures

? ? ? ? ? ? ? ? scheduledFutures = (Set<ScheduledFuture<?>>) BeanUtils.getProperty(taskRegistrar, "scheduledTasks");

? ? ? ? ? ? } catch (NoSuchFieldException e) {

? ? ? ? ? ? ? ? throw new SchedulingException("not found scheduledFutures field.");

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return scheduledFutures;

? ? }

? ? /**

? ? * 添加任務

? ? */

? ? public void addTriggerTask(String taskId, TriggerTask triggerTask) {

? ? ? ? if (taskFutures.containsKey(taskId)) {

? ? ? ? ? ? throw new SchedulingException("the taskId[" + taskId + "] was added.");

? ? ? ? }

? ? ? ? TaskScheduler scheduler = taskRegistrar.getScheduler();

? ? ? ? ScheduledFuture<?> future = scheduler.schedule(triggerTask.getRunnable(), triggerTask.getTrigger());

? ? ? ? getScheduledFutures().add(future);

? ? ? ? taskFutures.put(taskId, future);

? ? }

? ? /**

? ? * 取消任務

? ? */

? ? public void cancelTriggerTask(String taskId) {

? ? ? ? ScheduledFuture<?> future = taskFutures.get(taskId);

? ? ? ? if (future != null) {

? ? ? ? ? ? future.cancel(true);

? ? ? ? }

? ? ? ? taskFutures.remove(taskId);

? ? ? ? getScheduledFutures().remove(future);

? ? }

? ? /**

? ? * 重置任務

? ? */

? ? public void resetTriggerTask(String taskId, TriggerTask triggerTask) {

? ? ? ? cancelTriggerTask(taskId);

? ? ? ? addTriggerTask(taskId, triggerTask);

? ? }

? ? /**

? ? * 任務編號

? ? */

? ? public Set<String> taskIds() {

? ? ? ? return taskFutures.keySet();

? ? }

? ? /**

? ? * 是否存在任務

? ? */

? ? public boolean hasTask(String taskId) {

? ? ? ? return this.taskFutures.containsKey(taskId);

? ? }

? ? /**

? ? * 任務調度是否已經初始化完成

? ? */

? ? public boolean inited() {

? ? ? ? return this.taskRegistrar != null && this.taskRegistrar.getScheduler() != null;

? ? }

}

? 在項目啟動后就自動開啟任務的操作類如下:

package com.fongtech.cli.admin.tasktime;

import com.fongtech.cli.admin.service.IAuthLoginService;

import com.fongtech.cli.admin.service.IBackupsService;

import com.fongtech.cli.admin.service.IDictionnaryEntryService;

import com.fongtech.cli.mbg.model.entity.AuthLogin;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.CommandLineRunner;

import org.springframework.core.annotation.Order;

import org.springframework.scheduling.config.TriggerTask;

import org.springframework.scheduling.support.CronTrigger;

import org.springframework.stereotype.Component;

/**

* 項目啟動后執(zhí)行沽一,

*/

@Slf4j

@Component

@Order(value = 1)

public class CmdRunner implements CommandLineRunner {

? ? @Autowired

? ? private DefaultSchedulingConfigurer defaultSchedulingConfigurer;

? ? @Autowired

? ? private IDictionnaryEntryService dictionnaryEntryService;

? ? @Autowired

? ? private IBackupsService backupsService;

? ? @Autowired

? ? private IAuthLoginService authLoginService;

? ? @Override

? ? public void run(String... args) throws Exception {

? ? ? ? log.info("------按照預設備份周期啟動數據庫備份定時任務");

? ? ? ? while (!defaultSchedulingConfigurer.inited())

? ? ? ? {

? ? ? ? ? ? try {

? ? ? ? ? ? ? ? Thread.sleep(100);

? ? ? ? ? ? } catch (InterruptedException e) {

? ? ? ? ? ? ? ? e.printStackTrace();

? ? ? ? ? ? } finally {

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? String cron = dictionnaryEntryService.getEntryValueByName("CRON_VALUE");

? ? ? ? //默認按照管理員用戶權限執(zhí)行備份任務

? ? ? ? AuthLogin authLogin = authLoginService.query().eq(AuthLogin::getLogin_user, "admin").getOne();

? ? ? ? //啟動線程盖溺,按照原表內的時間執(zhí)行備份任務

? ? ? ? defaultSchedulingConfigurer.addTriggerTask("task",

? ? ? ? ? ? ? ? new TriggerTask(

? ? ? ? ? ? ? ? ? ? ? ? () -> System.out.println("=====----------啟動定時任務=-----------");,

? ? ? ? ? ? ? ? ? ? ? ? new CronTrigger(cron)));

? ? }

}

? 暫停定時任務:

defaultSchedulingConfigurer.cancelTriggerTask("task");

龍華大道1號http://www.kinghill.cn/LongHuaDaDao1Hao/index.html

?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市铣缠,隨后出現的幾起案子烘嘱,更是在濱河造成了極大的恐慌,老刑警劉巖蝗蛙,帶你破解...
    沈念sama閱讀 212,718評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蝇庭,死亡現場離奇詭異,居然都是意外死亡捡硅,警方通過查閱死者的電腦和手機哮内,發(fā)現死者居然都...
    沈念sama閱讀 90,683評論 3 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來病曾,“玉大人牍蜂,你說我怎么就攤上這事漾根。” “怎么了鲫竞?”我有些...
    開封第一講書人閱讀 158,207評論 0 348
  • 文/不壞的土叔 我叫張陵辐怕,是天一觀的道長。 經常有香客問我从绘,道長寄疏,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,755評論 1 284
  • 正文 為了忘掉前任僵井,我火速辦了婚禮陕截,結果婚禮上,老公的妹妹穿的比我還像新娘批什。我一直安慰自己农曲,他們只是感情好,可當我...
    茶點故事閱讀 65,862評論 6 386
  • 文/花漫 我一把揭開白布驻债。 她就那樣靜靜地躺著乳规,像睡著了一般。 火紅的嫁衣襯著肌膚如雪合呐。 梳的紋絲不亂的頭發(fā)上暮的,一...
    開封第一講書人閱讀 50,050評論 1 291
  • 那天,我揣著相機與錄音淌实,去河邊找鬼冻辩。 笑死,一個胖子當著我的面吹牛拆祈,可吹牛的內容都是我干的恨闪。 我是一名探鬼主播,決...
    沈念sama閱讀 39,136評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼缘屹,長吁一口氣:“原來是場噩夢啊……” “哼凛剥!你這毒婦竟也來了侠仇?” 一聲冷哼從身側響起轻姿,我...
    開封第一講書人閱讀 37,882評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎逻炊,沒想到半個月后互亮,有當地人在樹林里發(fā)現了一具尸體,經...
    沈念sama閱讀 44,330評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡余素,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,651評論 2 327
  • 正文 我和宋清朗相戀三年豹休,在試婚紗的時候發(fā)現自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片桨吊。...
    茶點故事閱讀 38,789評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡威根,死狀恐怖凤巨,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情洛搀,我是刑警寧澤敢茁,帶...
    沈念sama閱讀 34,477評論 4 333
  • 正文 年R本政府宣布,位于F島的核電站留美,受9級特大地震影響彰檬,放射性物質發(fā)生泄漏。R本人自食惡果不足惜谎砾,卻給世界環(huán)境...
    茶點故事閱讀 40,135評論 3 317
  • 文/蒙蒙 一逢倍、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧景图,春花似錦较雕、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,864評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至忘晤,卻和暖如春宛蚓,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背设塔。 一陣腳步聲響...
    開封第一講書人閱讀 32,099評論 1 267
  • 我被黑心中介騙來泰國打工凄吏, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人闰蛔。 一個月前我還...
    沈念sama閱讀 46,598評論 2 362
  • 正文 我出身青樓痕钢,卻偏偏與公主長得像,于是被迫代替她去往敵國和親序六。 傳聞我的和親對象是個殘疾皇子任连,可洞房花燭夜當晚...
    茶點故事閱讀 43,697評論 2 351