Java定时任务技术趋势

背景

定时任务是每个业务常见的需求,比如每分钟扫描超时支付的订单,每小时清理一次数据库历史数据,每天统计前一天的数据并生成报表等等。

1. Java中自带的解决方案

1.1 使用Timer

创建java.util.TimerTask任务,在run方法中实现业务逻辑。通过java.util.Timer进行调度,支持按照固定频率执行。所有的TimerTask是在同一个线程中串行执行,相互影响。也就是说,对于同一个Timer里的多个TimerTask任务,如果一个TimerTask任务在执行中,其它TimerTask即使到达执行的时间,也只能排队等待。如果有异常产生,线程将退出,整个定时任务就失败。

import java.util.Timer;
import java.util.TimerTask;

public class TestTimerTask {   
    
    public static void main(String[] args) {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.out.println("hell world");
            }
        };
        Timer timer = new Timer();
        timer.schedule(timerTask, 10, 3000);
    }  
    
}

1.2 使用ScheduledExecutorService

基于线程池设计的定时任务解决方案,每个调度任务都会分配到线程池中的一个线程去执行,解决Timer定时器无法并发执行的问题,支持fixedRate和fixedDelay。

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TestTimerTask {

    public static void main(String[] args) {
        ScheduledExecutorService ses = Executors.newScheduledThreadPool(5);
        //按照固定频率执行,每隔5秒跑一次
        ses.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello fixedRate");
            }
        }, 0, 5, TimeUnit.SECONDS);
        
        //按照固定延时执行,上次执行完后隔3秒再跑
        ses.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello fixedDelay");
            }
        }, 0, 3, TimeUnit.SECONDS);
    }
    
}

2. Spring中自带的解决方案

Springboot中提供了一套轻量级的定时任务工具Spring Task,通过注解可以很方便的配置,支持cron表达式、fixedRate、fixedDelay。

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
public class MyTask {
    
    /**
     * 每分钟的第30秒跑一次
     */
    @Scheduled(cron = "30 * * * * ?")
    public void task1() throws InterruptedException {
        System.out.println("hello cron");
    }

    /**
     * 每隔5秒跑一次
     */
    @Scheduled(fixedRate = 5000)
    public void task2() throws InterruptedException {
        System.out.println("hello fixedRate");
    }

    /**
     * 上次跑完隔3秒再跑
     */
    @Scheduled(fixedDelay = 3000)
    public void task3() throws InterruptedException {
        System.out.println("hello fixedDelay");
    }

}

Spring Task相对于上面提到的两种解决方案,最大的优势就是支持cron表达式,可以处理按照标准时间固定周期执行的业务,比如每天几点几分执行。

3. 业务幂等解决方案

现在的应用基本都是分布式部署,所有机器的代码都是一样的,前面介绍的Java和Spring自带的解决方案,都是进程级别的,每台机器在同一时间点都会执行定时任务。这样会导致需要业务幂等的定时任务业务有问题,比如每月定时给用户推送消息,就会推送多次。

于是,很多应用很自然的就想到了使用分布式锁的解决方案。即每次定时任务执行之前,先去抢锁,抢到锁的执行任务,抢不到锁的不执行。怎么抢锁,又是五花八门,比如使用DB、zookeeper、redis。

3.1 使用DB或者Zookeeper抢锁

使用DB或者Zookeeper抢锁的架构差不多,原理如下:

  1. 定时时间到了,在回调方法里,先去抢锁。
  2. 抢到锁,则继续执行方法,没抢到锁直接返回。
  3. 执行完方法后,释放锁。

示例代码如下:

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值