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í)體類(lèi)對(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)類(lèi)加上@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)度類(lèi),能夠開(kāi)啟線程池進(jìn)行任務(wù)調(diào)度。
ThreadPoolTaskScheduler.schedule()方法會(huì)創(chuàng)建一個(gè)定時(shí)計(jì)劃ScheduledFuture,在這個(gè)方法需要添加兩個(gè)參數(shù),Runnable(線程接口類(lèi)) 和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ù)類(lèi),也持久化到數(shù)據(jù)庫(kù),然后,threadPoolTaskScheduler.schedule要的業(yè)務(wù)類(lèi),可通過(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)文章
Mybatis的TypeHandler實(shí)現(xiàn)數(shù)據(jù)加解密詳解
這篇文章主要介紹了Mybatis基于TypeHandler實(shí)現(xiàn)敏感數(shù)據(jù)加密詳解,Typehandler是mybatis提供的一個(gè)接口,通過(guò)實(shí)現(xiàn)這個(gè)接口,可以實(shí)現(xiàn)jdbc類(lèi)型數(shù)據(jù)和java類(lèi)型數(shù)據(jù)的轉(zhuǎn)換,需要的朋友可以參考下2024-01-01
Mybatis-plus常見(jiàn)的坑@TableField不生效問(wèn)題
這篇文章主要介紹了Mybatis-plus常見(jiàn)的坑@TableField不生效問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
springcloud-gateway整合jwt+jcasbin實(shí)現(xiàn)權(quán)限控制的詳細(xì)過(guò)程
這篇文章主要介紹了springcloud-gateway整合jwt+jcasbin實(shí)現(xiàn)權(quán)限控制,基于springboot+springcloud+nacos的簡(jiǎn)單分布式項(xiàng)目,項(xiàng)目交互采用openFeign框架,單獨(dú)提取出來(lái)成為一個(gè)獨(dú)立的model,需要的朋友可以參考下2023-02-02
Java實(shí)現(xiàn)爬取往期所有雙色球開(kāi)獎(jiǎng)結(jié)果功能示例
這篇文章主要介紹了Java實(shí)現(xiàn)爬取往期所有雙色球開(kāi)獎(jiǎng)結(jié)果功能,涉及Java網(wǎng)頁(yè)抓取、正則替換、文件讀寫(xiě)等相關(guān)操作技巧,需要的朋友可以參考下2018-07-07

