java的常用定时任务的几种方式?

Java基本的定时任务,一般有这几种方式:
一、Timer
 1 public class Timer{
 2     static int index=0;
 3     public static void main(String[] args){
 4         Timer timer=new Timer();
 5             timer.schedule(new TimerTask() {
 6                 @Override
 7                 public void run() {
 8                     index++;
 9                     System.out.println("你好");
10                     if (index>100){
11                         timer.cancel();
12                     }
13                 }
14             },0,1000);
15     }      
16 }

通过往Timer提交一个TimerTask的任务,同时指定多久后开始执行以及执行周期,就可以周期执行任务。

二、Threa线程
 1 public class ThreadTest implements Runnable{
 2     static int i=0;
 3     @Override
 4     public void run() {
 5         Boolean t=true;
 6         while (t){
 7             i++;
 8             try {
 9                 if (i<100) {
10                     Thread.sleep(1000);
11                     System.out.println("你好");
12                 }else{
13                     t=false;
14                 }
15             } catch (InterruptedException e) {
16                 e.printStackTrace();
17             }
18         }
19     }
20     public static void main(String[] args){
21         ThreadTest test=new ThreadTest();
22         Thread t=new Thread(test);
23         t.start();
24     }

通过创建一个线程,让它在while循环里一直运行着,通过sleep方法来达到定时任务的效果。
三、Sping的@Scheduled注解定时
1    @Scheduled(fixedDelay = 5000)
2     public void note(){
3         System.out.println("你好");
4     }

注解中指定的属性名称是fixedRate,是指以固定频率(周期)执行任务,这个周期是以上一个任务开始时间为基准。

1     @Scheduled(cron="0 0 8 * * ?")
2     public void note(){
3         System.out.println("你好");
4     }

注解中指定的属性名称是cron,指定时调用,cron的参数依次指:

  • 秒(0~59)
  •   分钟(0~59)
  •   小时(0~23)
  •   天(月)(0~31,但是你需要考虑你月的天数)
  •   月(0~11)
  •   天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
  •   年份(1970-2099)

四、分布式定时框架LTS

 LTS 源码地址: https://github.com/ltsopensource/light-task-scheduler

实例源码:4种demo包括纯java、xml配置、注解配置、springboot

LTS 代码例子地址:https://github.com/ltsopensource/lts-examples/tree/master/lts-example-jobclient