java 定时任务实现方式

简介

  1. jdk之Timer
  2. jdk之ScheduledThreadPoolExecutor
  3. spring之TaskScheduler
  4. quartz

一. jdk之Timer

  1. schedule(TimerTask task, long delay) 延迟 delay 毫秒 执行
  2. schedule(TimerTask task, Date time) 特定时间执行
  3. schedule(TimerTask task, long delay, long period) 延迟 delay 毫秒 执行并每隔period 毫秒 执行一次
// 延迟2秒, 每隔3秒打印一次当前时间
public static void main(String[] args) {
    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            System.out.println(LocalDateTime.now());
        }
    }, 2000L, 3000L);
}

二. jdk之ScheduledThreadPoolExecutor

ScheduledExecutorService 接口实现类
ScheduledExecutorService 是JAVA 1.5 后新增的定时任务接口,主要有以下几个方法。

1.  ScheduledFuture schedule(Runnable command,long delay, TimeUnit unit);
2.   ScheduledFuture schedule(Callable callable,long delay, TimeUnit unit);
3.  ScheduledFuture scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnitunit);
4.  ScheduledFuture scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnitunit);

// 延迟2秒, 每隔2秒钟打印一次当前时间
public static void main(String[] args) {
    ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
    scheduledThreadPoolExecutor.scheduleAtFixedRate(()->System.out.println(LocalDateTime.now()), 2L, 2L, TimeUnit.SECONDS);
}

三. spring之TaskScheduler

介绍: 轻量级quartz, 使用起来简单
使用方式:

  1. 配置式


    

  1. 注解式(最常用)
  • 先启用注解
    spring项目需要再配置文件中启用

// 启用注解
 

springboot项目需要在启动类中启用注解

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
// 启用注解
@EnableScheduling
public class SpringbootDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootDemoApplication.class, args);
    }
}
  • 再使用注解和cron表达式
// 每隔5秒钟执行一次test方法
@Scheduled(cron = "0/5 * * * * ?")
public void test() {
    System.out.println(LocalDateTime.now());
}
  1. 编程式(略…)

四. quartz

你可能感兴趣的:(工具类)