Java中四種建立定時任務的方式

在開發中,建立定時任務的方式有不少,下面簡單介紹四種常見的方式:Runnable,TimerTask,線程池ScheduledExecutorService,Quartz。java

1.使用Runnableweb

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.使用TimerTaskide

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.使用線程池ScheduledExecutorServicesvg

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.使用Quartzui

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以下:spa

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()));
    }
}
相關文章
相關標籤/搜索