java定時任務實現(xiàn)的4種方式小結
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í)行了=======================");
}
}
//下面是開啟
@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定時任務調(diào)度器
配置
@Configuration
public class QuartzConfig {
@Resource
private ScheduleTask scheduleTask;
/**
* 配置定時任務1
* @return
*/
@Bean(name="firstJobDetail")
public MethodInvokingJobDetailFactoryBean firstJobDetail(){
MethodInvokingJobDetailFactoryBean method = new MethodInvokingJobDetailFactoryBean();
// 為需要執(zhí)行的實體類對應的對象
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);
// 設置任務啟動延遲
simpleBean.setStartDelay(1000);
// 每1秒執(zhí)行一次
simpleBean.setRepeatInterval(1000);
//設置重復計數(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í)行的任務
@Component
public class ScheduleTask {
public void test() {
System.out.println("====================================");
}
}
總結:
還有其他方式可以實現(xiàn)定時任務的方式,可以貼出來,討論討
補充知識:SpringBoot定時任務簡單使用和自定義開啟關閉修改周期
一、簡單使用
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ù)可以接受兩種定時的設置,一種是我們常用的cron="*/6 * * * * ?",一種是 fixedRate = 6000,兩種都表示每隔六秒打印一下內(nèi)容。
fixedRate 說明
@Scheduled(fixedRate = 6000) :上一次開始執(zhí)行時間點之后6秒再執(zhí)行
@Scheduled(fixedDelay = 6000) :上一次執(zhí)行完畢時間點之后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)在時間:" + dateFormat.format(new Date()));
}
}
3.啟動類加上@EnableScheduling注解。
@SpringBootApplication(exclude = MongoAutoConfiguration.class)
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
4.運行結果
this is scheduler task runing Thu Jul 18 10:59:06 CST 2019 現(xiàn)在時間:10:59:10 this is scheduler task runing Thu Jul 18 10:59:12 CST 2019 現(xiàn)在時間:10:59:16 this is scheduler task runing Thu Jul 18 10:59:18 CST 2019 現(xiàn)在時間:10:59:22 this is scheduler task runing Thu Jul 18 10:59:24 CST 2019 現(xiàn)在時間:10:59:28
以上就是定時任務的簡單使用。但是有時候,定時任務需要關閉,和開啟,或者修改定時任務的運行周期,可以使用下面的方式實現(xiàn).
二、高級使用,自定義定時任務,關閉,開啟,修改周期
1.說明
ThreadPoolTaskScheduler:線程池任務調(diào)度類,能夠開啟線程池進行任務調(diào)度。
ThreadPoolTaskScheduler.schedule()方法會創(chuàng)建一個定時計劃ScheduledFuture,在這個方法需要添加兩個參數(shù),Runnable(線程接口類) 和CronTrigger(定時任務觸發(fā)器)
在ScheduledFuture中有一個cancel可以停止定時任務。
@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);// 先停止,在開啟.
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());
}
}
}
如果想,做成后臺管理,添加刪除定時任務,可以將定時任務,持久化到數(shù)據(jù)庫,自定義開發(fā)MyRunnable定時任務的業(yè)務類,也持久化到數(shù)據(jù)庫,然后,threadPoolTaskScheduler.schedule要的業(yè)務類,可通過反射實例化出來,傳遞,然后,通過url,id參數(shù),來開啟,關閉,刪除,對應的定時任務。
以上這篇java定時任務實現(xiàn)的4種方式小結就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Mybatis的TypeHandler實現(xiàn)數(shù)據(jù)加解密詳解
這篇文章主要介紹了Mybatis基于TypeHandler實現(xiàn)敏感數(shù)據(jù)加密詳解,Typehandler是mybatis提供的一個接口,通過實現(xiàn)這個接口,可以實現(xiàn)jdbc類型數(shù)據(jù)和java類型數(shù)據(jù)的轉(zhuǎn)換,需要的朋友可以參考下2024-01-01
Mybatis-plus常見的坑@TableField不生效問題
這篇文章主要介紹了Mybatis-plus常見的坑@TableField不生效問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
springcloud-gateway整合jwt+jcasbin實現(xiàn)權限控制的詳細過程
這篇文章主要介紹了springcloud-gateway整合jwt+jcasbin實現(xiàn)權限控制,基于springboot+springcloud+nacos的簡單分布式項目,項目交互采用openFeign框架,單獨提取出來成為一個獨立的model,需要的朋友可以參考下2023-02-02

