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());
      }
    }, 1000, 2000, 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()));
  }
}

java定时任务实现的4种方式小结

扫一扫手机访问