Java中四种创建定时任务的方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ceovip/article/details/82734043

在开发中,创建定时任务的方式有很多,下面简单介绍四种常见的方式:Runnable,TimerTask,线程池ScheduledExecutorService,Quartz。

1.使用Runnable

    private static void testRunnable() {
        final long timeInterval = 1000;

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    System.out.println("Hello, XXX " + Thread.currentThread());
                    try {
                        Thread.sleep(timeInterval);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Thread thread = new Thread(runnable);
        thread.start();
    }

2.使用TimerTask

private static void testTimerTask() {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Hello, " + Thread.currentThread());
            }
        };

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(timerTask, 0, 1500);
    }

3.使用线程池ScheduledExecutorService

    private static void testExecutorService() {
        long initialDelay = 0;
        long period = 1;
        TimeUnit unit = TimeUnit.SECONDS;

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello, " + Thread.currentThread());
            }
        };

        ScheduledExecutorService service = Executors
                .newSingleThreadScheduledExecutor();
        service.scheduleAtFixedRate(runnable, initialDelay, period, unit);
    }

4.使用Quartz

    private static void testQuartz() throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(MySimpleJob.class).withIdentity("job1", "group1").build();
        //创建触发器,每5秒钟执行一次
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1")
        .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever())
        .build();

        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();

        //将任务及其触发器放入调度器
        scheduler.scheduleJob(jobDetail, trigger);
        //调度器开始调度任务
        scheduler.start();
    }

MySimpleJob如下:

package com.li.test;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/*
 * 实现了org.quartz.Job接口的类
 * 不要和TestTask写在一个文件夹里面,否则execute不会运行。
 */

public class MySimpleJob implements org.quartz.Job {

    public MySimpleJob() {
    }

    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); 
        System.out.println("MySimpleJob execute-->" + sdf.format(new Date()));
    }
}

猜你喜欢

转载自blog.csdn.net/ceovip/article/details/82734043