java定時(shí)任務(wù)實(shí)現(xiàn)的4種方式小結(jié)
1. java自帶的Timer
Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("Time's up!"); } },3*1000,1000);
2.ScheduledThreadPool-線程池
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2); scheduledThreadPool.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("========================="); } }, 1000, 2000, TimeUnit.MILLISECONDS); scheduledThreadPool.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println(System.currentTimeMillis()+"<><>"+System.nanoTime()); } }, 1000, 2000, TimeUnit.MILLISECONDS);
3.使用注解的形式:@Scheduled
@Component public class SpringScheduled { @Scheduled(initialDelay = 2000,fixedDelay = 5000) public void doSomething() { System.out.println("Spring自帶的Scheduled執(zhí)行了======================="); } } //下面是開(kāi)啟 @SpringBootApplication @EnableScheduling public class DemoApplication { public static void main(String[] args) throws InterruptedException { SpringApplication application = new SpringApplication(DemoApplication.class); application.addListeners(new ContextRefreshedEventListener()); application.run(args); } }
4.使用Quartz定時(shí)任務(wù)調(diào)度器
配置
@Configuration public class QuartzConfig { @Resource private ScheduleTask scheduleTask; /** * 配置定時(shí)任務(wù)1 * @return */ @Bean(name="firstJobDetail") public MethodInvokingJobDetailFactoryBean firstJobDetail(){ MethodInvokingJobDetailFactoryBean method = new MethodInvokingJobDetailFactoryBean(); // 為需要執(zhí)行的實(shí)體類對(duì)應(yīng)的對(duì)象 method.setTargetObject(scheduleTask); // 需要執(zhí)行的方法 method.setTargetMethod("test"); // 是否并發(fā)執(zhí)行 method.setConcurrent(false); return method; } /** * 配置觸發(fā)器1 * @param firstJobDetail * @return */ @Bean(name="firstTrigger") public SimpleTriggerFactoryBean firstTrigger(JobDetail firstJobDetail){ SimpleTriggerFactoryBean simpleBean = new SimpleTriggerFactoryBean(); simpleBean.setJobDetail(firstJobDetail); // 設(shè)置任務(wù)啟動(dòng)延遲 simpleBean.setStartDelay(1000); // 每1秒執(zhí)行一次 simpleBean.setRepeatInterval(1000); //設(shè)置重復(fù)計(jì)數(shù) //simpleBean.setRepeatCount(0); return simpleBean; } /** * 配置Scheduler */ @Bean(name = "scheduler") public SchedulerFactoryBean schedulerFactoryBean(Trigger firstTrigger){ SchedulerFactoryBean factoryBean = new SchedulerFactoryBean(); factoryBean.setTriggers(firstTrigger); return factoryBean; } }
要執(zhí)行的任務(wù)
@Component public class ScheduleTask { public void test() { System.out.println("===================================="); } }
總結(jié):
還有其他方式可以實(shí)現(xiàn)定時(shí)任務(wù)的方式,可以貼出來(lái),討論討
補(bǔ)充知識(shí):SpringBoot定時(shí)任務(wù)簡(jiǎn)單使用和自定義開(kāi)啟關(guān)閉修改周期
一、簡(jiǎn)單使用
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 參數(shù)可以接受兩種定時(shí)的設(shè)置,一種是我們常用的cron="*/6 * * * * ?",一種是 fixedRate = 6000,兩種都表示每隔六秒打印一下內(nèi)容。
fixedRate 說(shuō)明
@Scheduled(fixedRate = 6000) :上一次開(kāi)始執(zhí)行時(shí)間點(diǎn)之后6秒再執(zhí)行
@Scheduled(fixedDelay = 6000) :上一次執(zhí)行完畢時(shí)間點(diǎn)之后6秒再執(zhí)行
@Scheduled(initialDelay=1000, fixedRate=6000) :第一次延遲1秒后執(zhí)行,之后按fixedRate的規(guī)則每6秒執(zhí)行一次
@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("現(xiàn)在時(shí)間:" + dateFormat.format(new Date())); } }
3.啟動(dòng)類加上@EnableScheduling注解。
@SpringBootApplication(exclude = MongoAutoConfiguration.class) @EnableScheduling public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
4.運(yùn)行結(jié)果
this is scheduler task runing Thu Jul 18 10:59:06 CST 2019 現(xiàn)在時(shí)間:10:59:10 this is scheduler task runing Thu Jul 18 10:59:12 CST 2019 現(xiàn)在時(shí)間:10:59:16 this is scheduler task runing Thu Jul 18 10:59:18 CST 2019 現(xiàn)在時(shí)間:10:59:22 this is scheduler task runing Thu Jul 18 10:59:24 CST 2019 現(xiàn)在時(shí)間:10:59:28
以上就是定時(shí)任務(wù)的簡(jiǎn)單使用。但是有時(shí)候,定時(shí)任務(wù)需要關(guān)閉,和開(kāi)啟,或者修改定時(shí)任務(wù)的運(yùn)行周期,可以使用下面的方式實(shí)現(xiàn).
二、高級(jí)使用,自定義定時(shí)任務(wù),關(guān)閉,開(kāi)啟,修改周期
1.說(shuō)明
ThreadPoolTaskScheduler:線程池任務(wù)調(diào)度類,能夠開(kāi)啟線程池進(jìn)行任務(wù)調(diào)度。
ThreadPoolTaskScheduler.schedule()方法會(huì)創(chuàng)建一個(gè)定時(shí)計(jì)劃ScheduledFuture,在這個(gè)方法需要添加兩個(gè)參數(shù),Runnable(線程接口類) 和CronTrigger(定時(shí)任務(wù)觸發(fā)器)
在ScheduledFuture中有一個(gè)cancel可以停止定時(shí)任務(wù)。
@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);// 先停止,在開(kāi)啟. 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()); } } }
如果想,做成后臺(tái)管理,添加刪除定時(shí)任務(wù),可以將定時(shí)任務(wù),持久化到數(shù)據(jù)庫(kù),自定義開(kāi)發(fā)MyRunnable定時(shí)任務(wù)的業(yè)務(wù)類,也持久化到數(shù)據(jù)庫(kù),然后,threadPoolTaskScheduler.schedule要的業(yè)務(wù)類,可通過(guò)反射實(shí)例化出來(lái),傳遞,然后,通過(guò)url,id參數(shù),來(lái)開(kāi)啟,關(guān)閉,刪除,對(duì)應(yīng)的定時(shí)任務(wù)。
以上這篇java定時(shí)任務(wù)實(shí)現(xiàn)的4種方式小結(jié)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- Java spring定時(shí)任務(wù)詳解
- Java ScheduledExecutorService定時(shí)任務(wù)案例講解
- Java之SpringBoot定時(shí)任務(wù)案例講解
- Java 實(shí)現(xiàn)定時(shí)任務(wù)的三種方法
- java使用@Scheduled注解執(zhí)行定時(shí)任務(wù)
- Java中實(shí)現(xiàn)分布式定時(shí)任務(wù)的方法
- Java學(xué)習(xí)教程之定時(shí)任務(wù)全家桶
- JAVA使用quartz添加定時(shí)任務(wù),并依賴注入對(duì)象操作
- Java如何實(shí)現(xiàn)定時(shí)任務(wù)
- Java中定時(shí)任務(wù)的6種實(shí)現(xiàn)方式
相關(guān)文章
java 關(guān)鍵字static詳細(xì)介紹及如何使用
這篇文章主要介紹了java 關(guān)鍵字static詳細(xì)介紹及如何使用的相關(guān)資料,需要的朋友可以參考下2017-03-03java利用socket通信實(shí)現(xiàn)Modbus-RTU通信協(xié)議的示例代碼
這篇文章主要介紹了java利用socket通信實(shí)現(xiàn)Modbus-RTU通信協(xié)議的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04SpringBoot?DataSource數(shù)據(jù)源實(shí)現(xiàn)自動(dòng)配置流程詳解
這篇文章主要介紹了SpringBoot?DataSource數(shù)據(jù)源實(shí)現(xiàn)自動(dòng)配置流程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-10-10利用Java工具類Hutool實(shí)現(xiàn)驗(yàn)證碼校驗(yàn)功能
這篇文章主要介紹了利用Java工具類Hutool實(shí)現(xiàn)驗(yàn)證碼校驗(yàn)功能,利用Hutool實(shí)現(xiàn)驗(yàn)證碼校驗(yàn),校驗(yàn)的Servlet與今天的第一篇是一樣的,唯一就是驗(yàn)證碼的生成是不一樣的,利用Hutool生成驗(yàn)證碼更快捷.需要的朋友可以參考下2022-10-10SpringBoot用多線程批量導(dǎo)入數(shù)據(jù)庫(kù)實(shí)現(xiàn)方法
這篇文章主要介紹了SpringBoot用多線程批量導(dǎo)入數(shù)據(jù)庫(kù)實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2023-02-02學(xué)習(xí)不同 Java.net 語(yǔ)言中類似的函數(shù)結(jié)構(gòu)
這篇文章主要介紹了學(xué)習(xí)不同 Java.net 語(yǔ)言中類似的函數(shù)結(jié)構(gòu),函數(shù)式編程語(yǔ)言包含多個(gè)系列的常見(jiàn)函數(shù)。但開(kāi)發(fā)人員有時(shí)很難在語(yǔ)言之間進(jìn)行切換,因?yàn)槭煜さ暮瘮?shù)具有不熟悉的名稱。函數(shù)式語(yǔ)言傾向于基于函數(shù)范例來(lái)命名這些常見(jiàn)函數(shù)。,需要的朋友可以參考下2019-06-06Java常用數(shù)字工具類 數(shù)字轉(zhuǎn)漢字(1)
這篇文章主要為大家詳細(xì)介紹了Java常用數(shù)字工具類,數(shù)字轉(zhuǎn)漢字,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05Java簡(jiǎn)單數(shù)據(jù)加密方法DES實(shí)現(xiàn)過(guò)程解析
這篇文章主要介紹了Java簡(jiǎn)單數(shù)據(jù)加密方法DES實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12