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.  <V> ScheduledFuture<V> schedule(Callable<V> 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. 配置式
<task:scheduler id="myScheduler" pool-size="10" />
<task:scheduled-tasks scheduler="myScheduler">
    <task:scheduled ref="job" method="test" cron="0 * * * * ?"/>
</task:scheduled-tasks>
  1. 注解式(最常用)
  • 先启用注解
    spring项目需要再配置文件中启用
<task:scheduler id="myScheduler" pool-size="10" />
// 启用注解
<task:annotation-driven scheduler="myScheduler"/> 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值