Job定时任务的几种创建方式

以下介绍我所知的5种定时任务创建方式,仅供参考,互相学习哈。除了以下5种自己写的job任务,也可以使用已经开源的job任务调度平台,这些往往更加稳定。

1、使用线程创建Job定时任务。

这是最基础,最笨的一种方式,并不建议。代码示例:

public static class Demo01 {
	static long count = 0;

	public static void main(String[] args) {

        // 创建一个线程
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
                // 开始循环
				while (true) {
					try {
                        // 定时:每1000ms执行一次
						Thread.sleep(1000);
						count++;
						System.out.println(count);
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			}
		};
		Thread thread = new Thread(runnable);
        // 启动线程
		thread.start();
	}
}

2、使用TimerTask创建job定时任务。

示例代码:

public class JobTimerTask {

    static long count = 0;

    public static void main(String[] args) {
        // 定义TimerTask,写定时执行业务代码
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                count++;
                System.out.println(count);
            }
        };
        //创建timer对象设置间隔时间
        Timer timer = new Timer();
        // 间隔天数
        long delay = 0;
        // 间隔毫秒数
        long period = 1000;
        // 开启定时任务
        timer.scheduleAtFixedRate(timerTask, delay, period);
    }
}

3、使用线程池创建job定时任务。

示例代码:

public class JobScheduledExecutorService {

        public static void main(String[] args) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    // task to run goes here
                    System.out.println("Hello !!");
                }
            };
            ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
            // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间
            service.scheduleAtFixedRate(runnable, 1, 1, TimeUnit.SECONDS);
        }
}

4、使用Quartz框架

1)引入maven依赖

<dependencies>
<!-- quartz -->
<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>
</dependencies>

2)创建任务调度Bean

public class MyJob implements Job {

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("quartz MyJob date:" + System.currentTimeMillis());
    }
}

3)创建启动Bean

public class JobQuartz {

    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)
                //job的描述
                .withDescription("this is a ram job")
                //job 的name和group
                .withIdentity("ramJob", "ramGroup")
                .build();
        //任务运行的时间,SimpleSchedle类型触发器有效,3秒后启动任务
        long time= System.currentTimeMillis() + 3*1000L;
        Date statTime = new Date(time);
        //4.创建Trigger
        //使用SimpleScheduleBuilder或者CronScheduleBuilder
        Trigger t = TriggerBuilder.newTrigger()
                .withDescription("")
                .withIdentity("ramTrigger", "ramTriggerGroup")
                //.withSchedule(SimpleScheduleBuilder.simpleSchedule())
                //默认当前时间启动
                .startAt(statTime)
                //两秒执行一次,Quartz表达式,支持各种牛逼表达式
                .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?"))
                .build();
        //5.注册任务和定时器
        scheduler.scheduleJob(jb, t);
        //6.启动 调度器
        scheduler.start();
    }

5、使用springboot 的 @Scheduled 注解

示例代码:

@Component
// 主要用于标记配置类,兼备Component的效果。
@Configuration
// 开启定时任务
@EnableScheduling
public class SaticScheduleTask {

    // 添加定时任务,参数为cron表达式
    @Scheduled(cron = "0/5 * * * * ?")
    // 直接指定时间间隔,例如:5000ms
    // @Scheduled(fixedRate=5000) 
    private void configureTasks() {
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值