首页 > 技术文章 > java目前常用的几种定时任务

ElliottX4 2019-07-22 17:08 原文

java目前常用的几种定时任务


一、JDK自带的Timer

Timer是jdk中提供的一个定时器工具,使用的时候会在主线程之外起一个单独的线程执行指定的计划任务,可以指定执行一次或者反复执行多次。
TimerTask是一个实现了Runnable接口的抽象类,代表一个可以被Timer执行的任务。

 1 import org.junit.Test;
 2 import java.util.Timer;
 3 import java.util.TimerTask;
 4 
 5 public class TimerTest {
 6     @Test
 7     public void test(){
 8         Timer timer = new Timer();
 9         TimerTask timerTask = new TimerTask() {
10             @Override
11             public void run() {
12                 System.out.println("当前时间");//具体的任务
13             }
14         };
15         timer.schedule(timerTask1,1000,1000);//任务,开始时间ms,间隔ms
16         System.out.println("start");
17         try {
18             Thread.sleep(2000);//不停两秒,显示不出来,因为test情况下当前用户线程结束,可是定时任务1s还没开始,就被终止
19         }catch (Exception e) {
20 
21         }
22         System.out.println("end");
23     }
24 }

终止timer的方式

  1. 调用timer的cancle方法,
  2. 把timer线程设置成daemon线程,(new Timer(true)创建daemon线程),在jvm里,如果所有用户线程结束,那么守护线程也会被终止,不过这种方法一般不用。
  3. 当所有任务执行结束后,删除对应timer对象的引用,线程也会被终止。
  4. 调用System.exit方法终止程序

注意点

  1. 每一个Timer仅对应唯一一个线程。
  2. Timer不保证任务执行的十分精确, schedule如果某一次调度时间比较长,那么后面的时间会顺延和scheduleAtFixedRate(严格按照调度时间来的,如果某次调度时间太长了,那么会通过缩短间隔的方式保证下一次调度在预定时间执行)会有不同的时间差。
  3. Timer类的线程安全的
  4. jdk1.5之后,ScheduledExecutorService代替了Timer来实现任务调度,加入了线程池等特性。

二、spring的Task

Task底层的实现,使用的ScheduledExecutorService。

2.1、注解的形式

使用@EnableScheduling启动定时任务注解解析,之后@Schedule写在执行的任务上即可

[cron表达式详解](https://www.jianshu.com/p/1defb0f22ed1)

2.2、直接代码的形式

 1 @EnableScheduling
 2 public class Task {
 3 
 4     @Scheduled(zone = "Asia/Beijing",cron = "0/10 * * * * * *")//zone表示时区
 5     public void schedule4(){
 6     }
 7     /*
 8     fixedDelay对应的fixedDelayString支持字符串形式、占位符${}|#{}
 9      */
10     @Scheduled(fixedDelay = 5000)//上一次执行完毕时间点之后多长时间再执行
11     public void schedule1(){
12     }
13     @Scheduled(fixedRate = 5000)//上一次开始执行时间点之后多长时间再执行
14     public void schedule2(){
15     }
16     @Scheduled(initialDelay = 5000)//第一次延迟多长时间后再执行
17     public void schedule3(){
18     }
19 
20 }

 

TaskScheduler的子类

  1. ConcurrentTaskScheduler:以当前线程执行任务。如果任务简单,可以直接使用这个类来执行。快捷方便。

  2. DefaultManagedTaskScheduler:以当前线程执行任务,这是ConcurrentTaskScheduler的子类,添加了JNDI的支持。和ConcurrentTaskScheduler一样的用法,需要使用JNDI可以单独设置

  3. ThreadPoolTaskScheduler:TaskScheduler接口的默认实现类,多线程定时任务执行。<font color=#0075EA>可以设置执行线程池数(默认一个线程),使用前必须得先调用initialize()【初始化方法】,有shutDown()方法,执行完后可以关闭线程</font>。

  4. TimerManagerTaskScheduler:用于包装CommonJ中的TimerManager接口。在使用CommonJ进行调度时使用。(没有使用过)


三、Quartz


四、elastic-job分布式定时任务

基于Zookepper和Quartz开发,并且开源的Java分布式定时任务,解决Quartz不支持分布式的弊端,Elastic-Job采用分片的方式,是分布式调度解决方案。适用场景是:相对于流程比较简单,但是任务可以拆分到多个线程去执行。 每个任务都使用独立的线程池。

1 //注册zookeeper
2 @Bean(initMethod = "init")
3 public ZookeeperRegistryCenter regCenter( final String serverList,final String namespace) {
4      return new ZookeeperRegistryCenter(new ZookeeperConfiguration(serverList, namespace));
5  }

 

 1 //配置任务config
 2 @Configuration
 3 public class LoginOverdueJobConfig {
 4     @Resource
 5     private ZookeeperRegistryCenter regCenter;
 6 
 7     @Resource
 8     private JobEventConfiguration jobEventConfiguration;
 9 
10     private LiteJobConfiguration getLiteJobConfiguration(final Class<? extends SimpleJob> jobClass, final String cron, final int shardingTotalCount, final String shardingItemParameters) {
11         return LiteJobConfiguration.newBuilder(new SimpleJobConfiguration(JobCoreConfiguration.newBuilder(
12                 jobClass.getName(), cron, shardingTotalCount).shardingItemParameters(shardingItemParameters).build(), jobClass.getCanonicalName())).overwrite(true).build();
13     }
14 
15     @Bean(initMethod = "init")
16     public JobScheduler simpleCloudStorageJobScheduler(final LoginOverdueJob loginOverdueJob, @Value("${simpleJob.cron}") final String cron, @Value("${simpleJob.shardingTotalCount}") final int shardingTotalCount,
17                                                        @Value("${simpleJob.shardingItemParameters}") final String shardingItemParameters) {
18         return new SpringJobScheduler(loginOverdueJob, regCenter, getLiteJobConfiguration(loginOverdueJob.getClass(), cron, shardingTotalCount, shardingItemParameters), jobEventConfiguration);
19     }
20 }
1 //任务执行函数
2 @Component
3 public class LoginOverdueJob implements SimpleJob {
4     public void execute(ShardingContext shardingContext) {
5         
6     }
7 }

 

推荐阅读