Java中实现定时任务

一、 利用java.lang.Thread实现定时任务

public class TimedTask1 {
    private static Logger LOGGER = Logger.getLogger(TimedTask1.class);
    public static void main(String[] args) {
        final long timeInterval = 3000;
        Runnable runnable = new Runnable() {
            public void run() {
                while (true) {
                    LOGGER.info("定时任务时间到了,开始执行定时任务了!!!!!!!!!!!!");
                    try {
                        /*每隔3000毫秒执行一次*/
                        Thread.sleep(timeInterval);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }
}

运行结果如下:
这里写图片描述
二、 利用java.util.Timer实现定时任务

public class TimedTask2 {
    public static void main(String[] args) throws InterruptedException {
        Timer t = new Timer();
        /**
         * 参数1:执行的任务 
         * 参数2:首次执行的时间, new Date()为当前时间 
         * 参数3:每次执行任务的间隔时间(毫秒值)
         * 此时配置为:从当前时间开始,每隔3000毫秒执行一次
         */
        t.schedule(new MyTimerTask(), new Date(), 3000);
    }
}

class MyTimerTask extends TimerTask {
    private static Logger LOGGER = Logger.getLogger(MyTimerTask.class);
    @Override
    public void run() {
        LOGGER.info("定时任务时间到了,开始执行定时任务了!!!!!!!!!!!!");
    }
}

运行结果如下:
这里写图片描述
三、 利用java.util.concurrent.ScheduledExecutorService实现定时任务

public class TimedTask3 {
    private static Logger LOGGER = Logger.getLogger(TimedTask3.class);

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            public void run() {
                LOGGER.info("定时任务时间到了,开始执行定时任务了!!!!!!!!!!!!");
            }
        };
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        /**
         * 参数1:执行的任务
         * 参数2:首次执行的延时时间 
         * 参数3:定时执行的间隔时间 
         * 参数4:时间单位,SECONDS为秒
         */
        service.scheduleAtFixedRate(runnable, 3, 1, TimeUnit.SECONDS);
    }
}

运行结果如下:
这里写图片描述
四、 spring实现定时任务

public class TimedTask {
    private static Logger LOGGER = Logger.getLogger(TimedTask.class);
    public void task() {
        // 执行的定时任务
        LOGGER.info("----------开始执行定时任务!------------");
        LOGGER.info("定时任务时间到了,开始执行定时任务了!!!!!!!!!!!!");
        LOGGER.info("-----------定时任务执行完成!-------------");
    }

}

Spring配置文件如下:

<?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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="  
           http://www.springframework.org/schema/beans  
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
           http://www.springframework.org/schema/aop  
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/task
           http://www.springframework.org/schema/task/spring-task-3.0.xsd
           http://www.springframework.org/schema/context  
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- task任务扫描注解-->
    <task:annotation-driven/>  
    <!-- spring扫描定时任务的包路径 -->   
    <context:component-scan base-package="com.zh.task" />
    <!-- 创建定时任务的bean -->    
    <bean id="myTask" class="com.zh.task.TimedTask"></bean>

    <task:scheduled-tasks>
        <!-- 这里表示的是每天22:11执行一次,定时任务执行的方法就是myTask实例中的task()方法 -->
        <task:scheduled ref="myTask" method="task" cron="0 11 22 * * ?" />
    </task:scheduled-tasks>

</beans>

运行结果如下:
这里写图片描述

关于cron=”0 11 22 * * ?”使用的详解:

Cron表达式可以用于表示定时任务执行的具体时间,其表达式是一个字符串,以5或6个空格隔开,分为6或7个域,每一个域代表一个含义。
Cron有如下两种语法格式:

①   Seconds Minutes Hours DayofMonth Month DayofWeek Year
②   Seconds Minutes Hours DayofMonth Month DayofWeek
     (秒      分钟    小时      天     月份     星期      年)

每一个域可出现的字符如下:

Seconds:可出现“, - * /”四个字符,有效范围为0-59的整数 

Minutes:可出现“, - * /”四个字符,有效范围为0-59的整数 

Hours:可出现“, - * /”四个字符,有效范围为0-23的整数 

DayofMonth:可出现“, - * / ? L W C”八个字符,有效范围为0-31的整数 

Month:可出现“, - * /”四个字符,有效范围为1-12的整数或JAN-DEc 

DayofWeek:可出现“, - * / ? L C #”四个字符,有效范围为1-7的整数或SUN-SAT两个范围。1表示星期天,2表示星期一, 依次类推 

Year:可出现“, - * /”四个字符,有效范围为1970-2099

每一个域都使用数字,但还可以出现如下特殊字符,它们的含义是:

(1)“*”:表示匹配该域的任意值,假如在Minutes域使用*, 即表示每分钟都会触发事件。

(2)“?”:只能用在DayofMonth和DayofWeek两个域。它也匹配域的任意值,但实际不会。因为DayofMonth和DayofWeek会相互影响。例如想在每月的20日触发调度,不管20日到底是星期几,则只能使用如下写法: 13 13 15 20 * ?, 其中最后一位只能用?,而不能使用*,如果使用*表示不管星期几都会触发,实际上并不是这样。 

(3)“-”:表示范围,例如在Minutes域使用5-20,表示从5分到20分钟每分钟触发一次 

(4)“/”:表示起始时间开始触发,然后每隔固定时间触发一次,例如在Minutes域使用5/20,则意味着5分钟触发一次,而25,45等分别触发一次. 

(5)“,”:表示列出枚举值值。例如:在Minutes域使用5,20,则意味着在5和20分每分钟触发一次。 

(6)“L”:表示最后,只能出现在DayofWeek和DayofMonth域,如果在DayofWeek域使用5L,意味着在最后的一个星期四触发。 

(7)“W”:表示有效工作日(周一到周五),只能出现在DayofMonth域,系统将在离指定日期的最近的有效工作日触发事件。例如:在 DayofMonth使用5W,如果5日是星期六,则将在最近的工作日:星期五,即4日触发。如果5日是星期天,则在6日(周一)触发;如果5日在星期一到星期五中的一天,则就在5日触发。另外一点,W的最近寻找不会跨过月份 

(8)“LW”:这两个字符可以连用,表示在某个月最后一个工作日,即最后一个星期五。 

(9)“#”:用于确定每个月第几个星期几,只能出现在DayofMonth域。例如在4#2,表示某月的第二个星期三。

举例如下:
“0 0 10,14,16 * * ? ” ——— 每天上午10点,下午2点,4点
“0 0/30 9-17 * * ?” ——— 朝九晚五工作时间内每半小时
“0 0 12 ? * WED ” ——— 表示每个星期三中午12点
“0 0 12 * * ?” ——— 每天中午12点触发
“0 15 10 ? * *” ——— 每天上午10:15触发
“0 15 10 * * ?” ——— 每天上午10:15触发
“0 15 10 * * ? *” ———每天上午10:15触发
“0 15 10 * * ? 2005” ———2005年的每天上午10:15触发
“0 * 14 * * ?” ———在每天下午2点到下午2:59期间的每1分钟触发
“0 0/5 14 * * ?” ———在每天下午2点到下午2:55期间的每5分钟触发
“0 0/5 14,18 * * ?” ———在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
“0 0-5 14 * * ?” ———在每天下午2点到下午2:05期间的每1分钟触发
“0 10,44 14 ? 3 WED” ———每年三月的星期三的下午2:10和2:44触发
“0 15 10 ? * MON-FRI” ———周一至周五的上午10:15触发
“0 15 10 15 * ?” ———每月15日上午10:15触发
“0 15 10 L * ?” ———每月最后一日的上午10:15触发
“0 15 10 ? * 6L” ———每月的最后一个星期五上午10:15触发
“0 15 10 ? * 6L 2002-2005” ———2002年至2005年的每月的最后一个星期五上午10:15触发
“0 15 10 ? * 6#3” ———每月的第三个星期五上午10:15触发

扫描二维码关注公众号,回复: 2743378 查看本文章

五、使用Spring整合Quartz完成定时任务
项目使用jar包(spring核心包不再列出)

<dependency>
    <groupId>org.opensymphony.quartz</groupId>
    <artifactId>quartz</artifactId>
    <version>1.6.1</version>
</dependency>

spring配置文件如下所示:

<?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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

    <!-- 配置作业类 -->
    <bean id="buttonJob1" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> 
        <property name="targetObject"> 
            <bean class="com.button.timer.ButtonJob" /> 
        </property> 
        <property name="targetMethod" value="doJob1" /> 
        <property name="concurrent" value="false" />  <!-- 作业不并发调度 -->
    </bean> 
    <bean id="buttonJob2" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> 
        <property name="targetObject"> 
            <bean class="com.button.timer.ButtonJob" /> 
        </property> 
        <property name="targetMethod" value="doJob2" /> 
        <property name="concurrent" value="false" />  <!-- 作业不并发调度 -->
    </bean> 

    <!-- 第一种SimpleTriggerBean,只支持按照一定频度调用任务,如每隔30分钟运行一次。配置方式如下: --> 
    <bean id="doJob1Trigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> 
        <property name="jobDetail" ref="buttonJob1" /> 
        <property name="startDelay" value="0" />  <!-- 调度工厂实例化后,经过0秒开始执行调度 -->
        <property name="repeatInterval" value="2000" />  <!-- 每2秒调度一次 -->
    </bean> 
    <!-- 第二种CronTriggerBean,支持到指定时间运行一次,如每天12:00运行一次等。配置方式如下: -->
    <bean id="doJob2Trigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> 
        <property name="jobDetail" ref="buttonJob2" /> 
        <!-- 每天12:00运行一次 -->
        <property name="cronExpression" value="0 00 12 * * ?" /> 
    </bean> 
    <!-- 配置调度工厂  -->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> 
        <property name="triggers"> 
            <list> 
                <ref bean="doJob1Trigger" /> 
                <ref bean="doJob2Trigger" /> 
            </list> 
        </property> 
    </bean> 
</beans>

配置文件内容做一下说明:

Quartz的作业触发器有两种,根据需求选择合适的触发器:
1、两种触发器
org.springframework.scheduling.quartz.SimpleTriggerFactoryBean:支持按照一定频度调用任务,如每隔20秒运行一次。
org.springframework.scheduling.quartz.CronTriggerFactoryBean:支持到达指定时间运行一次,如每天0000运行一次等。
2、org.springframework.scheduling.quartz.SimpleTriggerFactoryBean:可以指定当调度工厂实例化后,经过多久开始执行调度。
3、org.springframework.scheduling.quartz.SchedulerFactoryBean:其参数triggers即为触发器的id。

执行任务类如下:

package com.button.timer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ButtonJob {
    private static final Logger LOGGER = LoggerFactory.getLogger(ButtonJob.class);
    public void doJob1() {
        System.out.println("ButtonJob1");
        LOGGER.info("工作开始了(ButtonJob1)");
    }
    public void doJob2() {
        System.out.println("ButtonJob2");
        LOGGER.info("工作开始了(ButtonJob2)");
    }
}

注:Quartz属于重量级的定时任务框架,若一般需求可以选用Spring提供的Task来完成所需要的定时任务。

猜你喜欢

转载自blog.csdn.net/qq_26709459/article/details/77806403