Springboot定時任務

2021-10-05 14:24:42 字數 1555 閱讀 1878

使用springboot基於註解來建立定時任務非常簡單,只需幾行**便可完成。 **如下:

@configuration // 1.主要用於標記配置類

@enablescheduling // 2.開啟定時任務

@slf4j

public class saticscheduletask

}

cron表示式引數分別表示:

秒(0~59) 例如0/5表示每5秒

分(0~59)

時(0~23)

日(0~31)的某天,需計算

月(0~11)

週幾( 可填1-7 或 sun/mon/tue/wed/thu/fri/sat)

@scheduled:除了支援靈活的引數表示式cron之外,還支援簡單的延時操作,例如 fixeddelay ,fixedrate 填寫相應的毫秒數即可。

定時任務預設使用單執行緒,新增多個定時任務程序會相互阻塞

@configuration

@enablescheduling

@slf4j

public class saticscheduletask

@scheduled(cron = "0/2 * * * * ?")

private void configuretask1() throws interruptedexception

}

可以新增配置類修改執行緒池的執行緒數(預設是1)

@configuration

@enablescheduling

public class schedulingconfiguration

}

預設使用單執行緒,使用schedulingconfiguration配置類可以修改預設執行緒數

@configuration // 1.主要用於標記配置類,兼備component的效果。

@enablescheduling // 2.開啟定時任務

@slf4j

public class dynamicscheduletask implements schedulingconfigurer

};trigger trigger = new trigger()

};taskregistrar.addtriggertask(task, trigger);

}}

專案中定時任務的處理邏輯要新增jediscluster取數不能使用多執行緒,如果使用單執行緒又會和其他的定時任務產生阻塞。

在public date nextexecutiontime(triggercontext triggercontext)方法中新增如下**,重新設定執行緒池

taskregistrar.setscheduler(executors.newscheduledthreadpool(1))

SpringBoot 定時任務

第一步 在啟動類中加入如下註解 enablescheduling public class public static void main string args 注意 enablescheduling必須加,否則無法開啟定時任務 第二步 建立定時任務 component public class ...

Spring boot定時任務

最近做專案,需要使用定時任務,半個小時去更新redis資料,於是便學習了一下經驗。希望可以幫到你們。定時任務可使用三種 created by fx on 2017 9 4.component allargsconstructor public class featuredatatask 實現乙個任務...

Spring boot 定時任務

1.在啟動類上加 enablescheduling註解 package com.example.demo import org.springframework.scheduling.annotation.enablescheduling enablescheduling public static ...