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

在开发中,创建定时任务的方式有很多,下面简单介绍四种常见的方式: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()));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值