1. 程式人生 > 程式設計 >java定時任務實現的4種方式小結

java定時任務實現的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());
      }
    },TimeUnit.MILLISECONDS);

3.使用註解的形式:@Scheduled

@Component
public class SpringScheduled {
 
  @Scheduled(initialDelay = 2000,fixedDelay = 5000)
  public void doSomething() {
    System.out.println("Spring自帶的Scheduled執行了=======================");
  }
} 
//下面是開啟
@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定時任務排程器

配置

@Configuration
public class QuartzConfig { 
 
  @Resource
  private ScheduleTask scheduleTask;
 
  /**
   * 配置定時任務1
   * @return
   */
  @Bean(name="firstJobDetail")
  public MethodInvokingJobDetailFactoryBean firstJobDetail(){
    MethodInvokingJobDetailFactoryBean method = new MethodInvokingJobDetailFactoryBean();
    // 為需要執行的實體類對應的物件
    method.setTargetObject(scheduleTask);
    // 需要執行的方法
    method.setTargetMethod("test");
    // 是否併發執行
    method.setConcurrent(false);
    return method;
  } 
 
  /**
   *  配置觸發器1
   *  @param firstJobDetail
   *  @return
   */
  @Bean(name="firstTrigger")
  public SimpleTriggerFactoryBean firstTrigger(JobDetail firstJobDetail){
    SimpleTriggerFactoryBean simpleBean = new SimpleTriggerFactoryBean();
    simpleBean.setJobDetail(firstJobDetail);
    // 設定任務啟動延遲
    simpleBean.setStartDelay(1000);
    // 每1秒執行一次
    simpleBean.setRepeatInterval(1000);
    //設定重複計數
    //simpleBean.setRepeatCount(0);
    return simpleBean;
  }
 
  /**
   * 配置Scheduler
   */
  @Bean(name = "scheduler")
  public SchedulerFactoryBean schedulerFactoryBean(Trigger firstTrigger){
    SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
    factoryBean.setTriggers(firstTrigger);
    return factoryBean;
  } 
}

要執行的任務

@Component
public class ScheduleTask {
 
  public void test() {
    System.out.println("====================================");
  }
 
}

總結:

還有其他方式可以實現定時任務的方式,可以貼出來,討論討

補充知識: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 引數可以接受兩種定時的設定,一種是我們常用的cron="*/6 * * * * ?",一種是 fixedRate = 6000,兩種都表示每隔六秒列印一下內容。

fixedRate 說明

@Scheduled(fixedRate = 6000) :上一次開始執行時間點之後6秒再執行

@Scheduled(fixedDelay = 6000) :上一次執行完畢時間點之後6秒再執行

@Scheduled(initialDelay=1000,fixedRate=6000) :第一次延遲1秒後執行,之後按fixedRate的規則每6秒執行一次

@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("現在時間:" + 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
現在時間:10:59:10
this is scheduler task runing Thu Jul 18 10:59:12 CST 2019
現在時間:10:59:16
this is scheduler task runing Thu Jul 18 10:59:18 CST 2019
現在時間:10:59:22
this is scheduler task runing Thu Jul 18 10:59:24 CST 2019
現在時間:10:59:28

以上就是定時任務的簡單使用。但是有時候,定時任務需要關閉,和開啟,或者修改定時任務的執行週期,可以使用下面的方式實現.

二、高階使用,自定義定時任務,關閉,開啟,修改週期

1.說明

ThreadPoolTaskScheduler:執行緒池任務排程類,能夠開啟執行緒池進行任務排程。

ThreadPoolTaskScheduler.schedule()方法會建立一個定時計劃ScheduledFuture,在這個方法需要新增兩個引數,Runnable(執行緒介面類) 和CronTrigger(定時任務觸發器)

在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());
    }
   }
}

如果想,做成後臺管理,新增刪除定時任務,可以將定時任務,持久化到資料庫,自定義開發MyRunnable定時任務的業務類,也持久化到資料庫,然後,threadPoolTaskScheduler.schedule要的業務類,可通過反射例項化出來,傳遞,然後,通過url,id引數,來開啟,關閉,刪除,對應的定時任務。

以上這篇java定時任務實現的4種方式小結就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。