Quartz 定时任务(Scheduler)的 3 种实现方式

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。

PS:第 3 种最简单。

一、引入 jar 。

   <!-- quartz 定时任务调度 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <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>

二 、实现方式 一

1. 定义好定时任务的业务内容:

package gentle.test;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author silence
 * @date 2018/7/17 11:37
 */
@Service("show")
public class Show implements Job {


    private static Logger _log = LoggerFactory.getLogger(Show.class);

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {

        _log.info("\n\n-------------------------------\n " +
                "It is running and the time is : " + new Date()+
                "\n-------------------------------\n");
    }

}

2. 声明定时任务,并关联业务实现类 。在 JobDetail jb = JobBuilder.newJob(Show.class) 中关联业务类 。

package gentle.test;


import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author silence
 * @date 2018/7/17 11:36
 */
@Service("schedulerTest")
public class SchedulerTest {


    private static Logger _log = LoggerFactory.getLogger(Scheduler.class);


    public static void main(String[] args) {

        try {

            //1.创建Scheduler的工厂
            SchedulerFactory sf = new StdSchedulerFactory();
            //2.从工厂中获取调度器实例
            Scheduler scheduler = sf.getScheduler();

            //3.创建JobDetail
            JobDetail jb = JobBuilder.newJob(Show.class) // Show 为一个job,是要执行的一个任务。
                    .withDescription("这是我的测试定时任务。") //job的描述
                    .withIdentity("jy2Job", "jy2Group") //job 的name和group
                    .build();

            //任务运行的时间,SimpleSchedle类型触发器有效
            long time = System.currentTimeMillis() + 3 * 1000L; // 3秒后启动任务
            Date statTime = new Date(time);

            //4.创建Trigger
            //使用SimpleScheduleBuilder或者CronScheduleBuilder
            Trigger t = TriggerBuilder.newTrigger()
                    .withDescription("")
                    .withIdentity("jyTrigger", "jyTriggerGroup")
                    //.withSchedule(SimpleScheduleBuilder.simpleSchedule())
                    .startAt(statTime)  //默认当前时间启动 ,也可以写为:.startNow();
                    .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")) //两秒执行一次
                    .build();

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

            //6.启动 调度器
            scheduler.start();
            _log.info("启动时间 : " + new Date());

        } catch (Exception e) {
            _log.info("定时任务出现异常 : " + e);
        }
    }
}

3. 运行成功:

 

实现方式 二 。

1. 定义好定时任务的业务内容:

package gentle.test;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author silence
 * @date 2018/7/17 11:37
 */
@Service("show")
public class Show implements Job {


    private static Logger _log = LoggerFactory.getLogger(Show.class);

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {

        _log.info("\n\n-------------------------------\n " +
                "It is running and the time is : " + new Date()+
                "\n-------------------------------\n");
    }

}

2. 定义好定时任务的触发类,调用业务类中的实现 。

package gentle.test;

import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

public class UserSyncTask {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    Show show;

    public void cronDepartmentsAndUsersJob() {

        logger.info("\n\n 定时--开始,当前时间: " + dateFormat().format(new Date()));
        try {
            show.execute(null);
        } catch (JobExecutionException e) {
            e.printStackTrace();
        }
        logger.info("\n\n 定时--结束,当前时间:" + dateFormat().format(new Date()));
    }

    private SimpleDateFormat dateFormat() {
        return new SimpleDateFormat("HH:mm:ss");
    }
}

3. 配置文件中 配置触发类和任务执行频率 。

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

    <!--定时任务触发类-->
    <bean id="userSyncTask" class="gentle.test.UserSyncTask"></bean>

    <!--执行频率-->
    <task:scheduled-tasks>
        <!--每 2 秒执行一次-->
        <task:scheduled ref="userSyncTask" method="cronDepartmentsAndUsersJob" cron="0/2 * * * * ?" />
    </task:scheduled-tasks>

</beans>

4. 运行成功:

 

实现方式 三 。

1. 引入 jar , 同上。

2. 运行类 代码中只要给 2 个注解就可以了:

@EnableScheduling  // 开启定时器、

@Scheduled(fixedDelay = 2000)  或者 @Scheduled(cron = "* * 2 * * ?")   // 每 2s 执行 1 次 。

代码:

package gentle.test;

import gentle.util.DateUtil;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 定时任务 -- 简版
 * @author silence
 * @date 2018/7/31 16:03
 */

@Component // 注册为一个bean
@EnableScheduling // 开启定时器
public class Sender {

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    @Scheduled(fixedDelay = 2000) // 每 2s 执行1次。
    public void send() {
        logger.info(" \n------------------------\n " +
                "定时任务内容 :" + DateUtil.dateFormat().format(new Date()) +
                "\n------------------------\n");
    }
}

3. 运行效果:

 

源码地址:定时任务demo

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值