Welcome everyone

定时任务的4种实现方式

java 汪明鑫 892浏览 0评论

Thread 方式

public class ThreadTask {
    static long count = 0;
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                        count++;
                        System.out.println(count);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }
}

 

TimerTask方式

先整一个task

public class MyTask extends TimerTask {
    @Override
    public void run() {
        System.out.println("hello world");
    }
}
public class TimerTest {
    public static void main(String[] args) {
        //创建定时器对象
        Timer t=new Timer();
        //在3秒后执行MyTask类中的run方法,后面每10秒跑一次
        t.schedule(new MyTask(), 3000,2000);
    }
}

 

ScheduledExecutorService方式

public class ScheduledThreadPoolExecutorTest {

    public static void main(String[] args){
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(8);
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello world");
            }
        }, 1, 2, TimeUnit.SECONDS);

    }

}

 

Quartz方式

先创建一个maven项目

引入依赖

<dependency>
      <groupId>org.quartz-scheduler</groupId>
      <artifactId>quartz</artifactId>
      <version>2.2.1</version>
    </dependency>
    <dependency>
      <groupId>org.quartz-scheduler</groupId>
      <artifactId>quartz-jobs</artifactId>
      <version>2.2.1</version>
    </dependency>

写一个Job类

public class MyJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("quartz MyJob date:" + new Date());
    }
}
public class App 
{
    public static void main( String[] args ) throws SchedulerException {
        //1.创建Scheduler的工厂
        SchedulerFactory sf = new StdSchedulerFactory();

        //2.从工厂中获取调度器实例
        Scheduler scheduler = sf.getScheduler();

        //3.创建JobDetail
        JobDetail jb = JobBuilder.newJob(MyJob.class)
                .withDescription("this is a job") //job的描述
                .withIdentity("MyJob", "MyGroup") //job 的name和group
                .build();

        long time=  System.currentTimeMillis() + 3*1000L; //3秒后启动任务
        Date startTime = new Date(time);

        //4.创建Trigger
        //使用SimpleScheduleBuilder或者CronScheduleBuilder
        Trigger t = TriggerBuilder.newTrigger()
                .withDescription("")
                .withIdentity("MyTrigger", "MyTriggerGroup")
                //.withSchedule(SimpleScheduleBuilder.simpleSchedule())
                .startAt(startTime)  //默认当前时间启动
                .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")) //两秒执行一次
                .build();

        //5.注册任务和定时器
        scheduler.scheduleJob(jb, t);

        //6.启动调度器
        scheduler.start();

    }
}

 

 

cron表达式比较常用,无论是Quartz,还是分布式定时任务elastic-job都要写cron表达式,不需要记,有一个在线转换cron表达式的网站
http://cron.qqe2.com/

 

 

其实定时任务的另外三种方式最终还是通过thread来实现

转载请注明:汪明鑫的个人博客 » 定时任务的4种实现方式

喜欢 (0)

说点什么

您将是第一位评论人!

提醒
avatar
wpDiscuz