Home > Java > javaTutorial > Java implements scheduled tasks Schedule

Java implements scheduled tasks Schedule

高洛峰
Release: 2016-12-16 13:11:26
Original
1418 people have browsed it

1.Java scheduled tasks can be implemented with the help of java.util.Timer

import java.util.Calendar;  
import java.util.Date;  
import java.util.Timer;  
import java.util.TimerTask;  
  
public class Test {  
    public static void main(String[] args) {  
        //timer1();  
        timer2();  
        //timer3();  
        //timer4();  
    }  
  
    // 第一种方法:设定指定任务task在指定时间time执行 schedule(TimerTask task, Date time)  
    public static void timer1() {  
        Timer timer = new Timer();  
        timer.schedule(new TimerTask() {  
            public void run() {  
                System.out.println("-------设定要指定任务--------");  
            }  
        }, 2000);// 设定指定的时间time,此处为2000毫秒  
    }  
  
    // 第二种方法:设定指定任务task在指定延迟delay后进行固定延迟peroid的执行  
    // schedule(TimerTask task, long delay, long period)  
    public static void timer2() {  
        Timer timer = new Timer();  
        timer.schedule(new TimerTask() {  
            public void run() {  
                System.out.println("-------设定要指定任务--------");  
            }  
        }, 1000, 1000);  
    }  
  
    // 第三种方法:设定指定任务task在指定延迟delay后进行固定频率peroid的执行。  
    // scheduleAtFixedRate(TimerTask task, long delay, long period)  
    public static void timer3() {  
        Timer timer = new Timer();  
        timer.scheduleAtFixedRate(new TimerTask() {  
            public void run() {  
                System.out.println("-------设定要指定任务--------");  
            }  
        }, 1000, 2000);  
    }  
     
    // 第四种方法:安排指定的任务task在指定的时间firstTime开始进行重复的固定速率period执行.  
    // Timer.scheduleAtFixedRate(TimerTask task,Date firstTime,long period)  
    public static void timer4() {  
        Calendar calendar = Calendar.getInstance();  
        calendar.set(Calendar.HOUR_OF_DAY, 12); // 控制时  
        calendar.set(Calendar.MINUTE, 0);       // 控制分  
        calendar.set(Calendar.SECOND, 0);       // 控制秒  
  
        Date time = calendar.getTime();         // 得出执行任务的时间,此处为今天的12:00:00  
  
        Timer timer = new Timer();  
        timer.scheduleAtFixedRate(new TimerTask() {  
            public void run() {  
                System.out.println("-------设定要指定任务--------");  
            }  
        }, time, 1000 * 60 * 60 * 24);// 这里设定将延时每天固定执行  
    }  
}
Copy after login

2. Java scheduled tasks can be implemented by thread waiting

/**  
 * 普通thread  
 * 这是最常见的,创建一个thread,然后让它在while循环里一直运行着,  
 * 通过sleep方法来达到定时任务的效果。这样可以快速简单的实现,代码如下:  
 * @author GT  
 *  
 */    
public class Task1 {    
    public static void main(String[] args) {    
        // run in a second    
        final long timeInterval = 1000;    
        Runnable runnable = new Runnable() {    
            public void run() {    
                while (true) {    
                    // ------- code for task to run    
                    System.out.println("Hello !!");    
                    // ------- ends here    
                    try {    
                        Thread.sleep(timeInterval);    
                    } catch (InterruptedException e) {    
                        e.printStackTrace();    
                    }    
                }    
            }    
        };    
        Thread thread = new Thread(runnable);    
        thread.start();    
    }    
}
Copy after login

3.Java can be implemented with java.util.concurrent.ScheduledExecutorService

import java.util.concurrent.Executors;    
import java.util.concurrent.ScheduledExecutorService;    
import java.util.concurrent.TimeUnit;    
    
/**  
 *   
 *   
 * ScheduledExecutorService是从Java SE5的java.util.concurrent里,做为并发工具类被引进的,这是最理想的定时任务实现方式。   
 * 相比于上两个方法,它有以下好处:  
 * 1>相比于Timer的单线程,它是通过线程池的方式来执行任务的   
 * 2>可以很灵活的去设定第一次执行任务delay时间  
 * 3>提供了良好的约定,以便设定执行的时间间隔  
 *   
 * 下面是实现代码,我们通过ScheduledExecutorService#scheduleAtFixedRate展示这个例子,通过代码里参数的控制,首次执行加了delay时间。  
 *   
 *   
 * @author GT  
 *   
 */    
public class Task3 {    
    public static void main(String[] args) {    
        Runnable runnable = new Runnable() {    
            public void run() {    
                // task to run goes here    
                System.out.println("Hello !!");    
            }    
        };    
        ScheduledExecutorService service = Executors    
                .newSingleThreadScheduledExecutor();    
        // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间    
        service.scheduleAtFixedRate(runnable, 10, 1, TimeUnit.SECONDS);    
    }    
}
Copy after login

4. Scheduled Tasks - Using Quartz

Quartz is another open source project of the OpenSymphony open source organization in the field of job scheduling. It can be combined with J2EE and J2SE applications or used alone. Quartz can be used to create simple or complex daily schedules for running ten, hundreds, or even tens of thousands of Jobs. Jobs can be made into standard Java components or EJBs.



CronTrigger configuration format:
Format: [Second] [Minute] [Hour] [Day] [Month] [Week] [Year]

Serial Number Description Is it required? Allowed values ​​Allowed wildcards

1 seconds is 0-59 , - * /

2 minutes is 0-59 , - * /

3 hours is 0-23 , - * /

4 Day is 1-31 , - * ? / L W

5 Month Yes 1-12 or JAN-DEC , - * /

6 Week Yes 1-7 or SUN-SAT , - * ? / L #

7 Year No Empty or 1970-2099 , - * /

Wildcard description:
* represents all values. For example: setting "*" on the minute field means it will trigger every minute.
? means no value is specified. The usage scenario is that you do not need to care about the current value of this field. For example: you want to trigger an operation on the 10th of each month, but you don't care what day of the week it is, so you need to set the field of the week position to "?" specifically set to 0 0 0 10* ?
- to represent the interval. For example, setting "10-12" on the hour means that it will be triggered at 10, 11, and 12 o'clock.
, means specifying multiple values, for example, setting "MON,WED,FRI" on the week field means triggering on Monday, Wednesday and Friday
/ is used for incremental triggering. For example, setting "5/15" above seconds means starting from 5 seconds and triggering every 15 seconds (5,20,35,50). Set '1/3' in the month field to start on the 1st of each month and trigger every three days.
L means the last word. In the day field setting, it represents the last day of the month (according to the current month, if it is February, it will also depend on whether it is a leap year), and in the week field it represents Saturday, which is equivalent to "7" or "SAT". If you add a number before "L", it means the last one of the data. For example, setting a format like "6L" on the week field means "the last Friday of this month"
W means the closest working day (Monday to Friday) to the specified date. For example, setting "15W" on the day field, Indicates that the working day closest to the 15th of each month triggers. If the 15th happens to be a Saturday, the trigger will be found on the nearest Friday (the 14th). If the 15th is a weekend, the trigger will be found on the nearest Monday (the 16th). If the 15th happens to be on a working day (Monday to Sunday) 5), it will be triggered on that day. If the specified format is "1W", it means that it is triggered on the nearest working day after the 1st of each month. If the 1st falls on a Saturday, it will be triggered on Monday the 3rd. (Note, only specific numbers can be set before "W", and the interval "-" is not allowed).

Tips

'L' and 'W' can be used in combination. If "LW" is set on the day field, it means that it is triggered on the last working day of the month (generally refers to salary payment)

# Serial number (indicating the day of the week of each month), for example, in the week Setting "6#3" on the field indicates the third Saturday of each month. Note that if "#5" is specified and there is no Saturday in the fifth week, this configuration will not be triggered (used on Mother's Day and Father's Day). It couldn’t be more appropriate)

Tips The setting of the week field is not case-sensitive if English letters are used. MON is the same as mon.


Common examples:

0 0 12 * * ? Triggered at 12 o'clock every day

0 15 10 ? * * Triggered at 10:15 every day

0 15 10 * * ? Triggered at 10:15 every day

0 15 10 * * ? * Triggered at 10:15 every day

0 15 10 * * ? 2005 Triggered at 10:15 every day in 2005

0 * 14 * * ? 每天下午的 2点到2点59分每分触发

0 0/5 14 * * ? 每天下午的 2点到2点59分(整点开始,每隔5分触发)

0 0/5 14,18 * * ? 每天下午的 2点到2点59分(整点开始,每隔5分触发)每天下午的 18点到18点59分(整点开始,每隔5分触发)

0 0-5 14 * * ? 每天下午的 2点到2点05分每分触发

0 10,44 14 ? 3 WED 3月分每周三下午的 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 每月的第三周的星期五开始触发

0 0 12 1/5 * ? 每月的第一个中午开始每隔5天触发一次

0 11 11 11 11 ? 每年的11月11号 11点11分触发(光棍节)

经过封装的管理类:

import java.text.ParseException;    
    
import org.quartz.CronTrigger;    
import org.quartz.JobDetail;    
import org.quartz.Scheduler;    
import org.quartz.SchedulerException;    
import org.quartz.SchedulerFactory;    
import org.quartz.impl.StdSchedulerFactory;    
    
/**  
 * 定时任务管理类  
 *  
 */    
public class QuartzManager {    
    private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();    
    private static String JOB_GROUP_NAME = "EXTJWEB_JOBGROUP_NAME";    
    private static String TRIGGER_GROUP_NAME = "EXTJWEB_TRIGGERGROUP_NAME";    
    
    /**  
     * 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名  
     *  
     * @param jobName  
     *            任务名  
     * @param jobClass  
     *            任务  
     * @param time  
     *            时间设置,参考quartz说明文档  
     * @throws SchedulerException  
     * @throws ParseException  
     */    
    public static void addJob(String jobName, String jobClass, String time) {    
        try {    
            Scheduler sched = gSchedulerFactory.getScheduler();    
            JobDetail jobDetail = new JobDetail(jobName, JOB_GROUP_NAME, Class.forName(jobClass));// 任务名,任务组,任务执行类    
            // 触发器    
            CronTrigger trigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME);// 触发器名,触发器组    
            trigger.setCronExpression(time);// 触发器时间设定    
            sched.scheduleJob(jobDetail, trigger);    
            // 启动    
            if (!sched.isShutdown()){    
                sched.start();    
            }    
        } catch (Exception e) {    
            e.printStackTrace();    
            throw new RuntimeException(e);    
        }    
    }    
    
    /**  
     * 添加一个定时任务  
     *  
     * @param jobName  
     *            任务名  
     * @param jobGroupName  
     *            任务组名  
     * @param triggerName  
     *            触发器名  
     * @param triggerGroupName  
     *            触发器组名  
     * @param jobClass  
     *            任务  
     * @param time  
     *            时间设置,参考quartz说明文档  
     * @throws SchedulerException  
     * @throws ParseException  
     */    
    public static void addJob(String jobName, String jobGroupName,    
            String triggerName, String triggerGroupName, String jobClass, String time){    
        try {    
            Scheduler sched = gSchedulerFactory.getScheduler();    
            JobDetail jobDetail = new JobDetail(jobName, jobGroupName, Class.forName(jobClass));// 任务名,任务组,任务执行类    
            // 触发器    
            CronTrigger trigger = new CronTrigger(triggerName, triggerGroupName);// 触发器名,触发器组    
            trigger.setCronExpression(time);// 触发器时间设定    
            sched.scheduleJob(jobDetail, trigger);    
        } catch (Exception e) {    
            e.printStackTrace();    
            throw new RuntimeException(e);    
        }    
    }    
    
    /**  
     * 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)  
     *  
     * @param jobName  
     * @param time  
     */    
    public static void modifyJobTime(String jobName, String time) {    
        try {    
            Scheduler sched = gSchedulerFactory.getScheduler();    
            CronTrigger trigger = (CronTrigger) sched.getTrigger(jobName, TRIGGER_GROUP_NAME);    
            if(trigger == null) {    
                return;    
            }    
            String oldTime = trigger.getCronExpression();    
            if (!oldTime.equalsIgnoreCase(time)) {    
                JobDetail jobDetail = sched.getJobDetail(jobName, JOB_GROUP_NAME);    
                Class objJobClass = jobDetail.getJobClass();    
                String jobClass = objJobClass.getName();    
                removeJob(jobName);    
    
                addJob(jobName, jobClass, time);    
            }    
        } catch (Exception e) {    
            e.printStackTrace();    
            throw new RuntimeException(e);    
        }    
    }    
    
    /**  
     * 修改一个任务的触发时间  
     *  
     * @param triggerName  
     * @param triggerGroupName  
     * @param time  
     */    
    public static void modifyJobTime(String triggerName,    
            String triggerGroupName, String time) {    
        try {    
            Scheduler sched = gSchedulerFactory.getScheduler();    
            CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerName, triggerGroupName);    
            if(trigger == null) {    
                return;    
            }    
            String oldTime = trigger.getCronExpression();    
            if (!oldTime.equalsIgnoreCase(time)) {    
                CronTrigger ct = (CronTrigger) trigger;    
                // 修改时间    
                ct.setCronExpression(time);    
                // 重启触发器    
                sched.resumeTrigger(triggerName, triggerGroupName);    
            }    
        } catch (Exception e) {    
            e.printStackTrace();    
            throw new RuntimeException(e);    
        }    
    }    
    
    /**  
     * 移除一个任务(使用默认的任务组名,触发器名,触发器组名)  
     *  
     * @param jobName  
     */    
    public static void removeJob(String jobName) {    
        try {    
            Scheduler sched = gSchedulerFactory.getScheduler();    
            sched.pauseTrigger(jobName, TRIGGER_GROUP_NAME);// 停止触发器    
            sched.unscheduleJob(jobName, TRIGGER_GROUP_NAME);// 移除触发器    
            sched.deleteJob(jobName, JOB_GROUP_NAME);// 删除任务    
        } catch (Exception e) {    
            e.printStackTrace();    
            throw new RuntimeException(e);    
        }    
    }    
    
    /**  
     * 移除一个任务  
     *  
     * @param jobName  
     * @param jobGroupName  
     * @param triggerName  
     * @param triggerGroupName  
     */    
    public static void removeJob(String jobName, String jobGroupName,    
            String triggerName, String triggerGroupName) {    
        try {    
            Scheduler sched = gSchedulerFactory.getScheduler();    
            sched.pauseTrigger(triggerName, triggerGroupName);// 停止触发器    
            sched.unscheduleJob(triggerName, triggerGroupName);// 移除触发器    
            sched.deleteJob(jobName, jobGroupName);// 删除任务    
        } catch (Exception e) {    
            e.printStackTrace();    
            throw new RuntimeException(e);    
        }    
    }    
    
    /**  
     * 启动所有定时任务  
     */    
    public static void startJobs() {    
        try {    
            Scheduler sched = gSchedulerFactory.getScheduler();    
            sched.start();    
        } catch (Exception e) {    
            e.printStackTrace();    
            throw new RuntimeException(e);    
        }    
    }    
    
    /**  
     * 关闭所有定时任务  
     */    
    public static void shutdownJobs() {    
        try {    
            Scheduler sched = gSchedulerFactory.getScheduler();    
            if(!sched.isShutdown()) {    
                sched.shutdown();    
            }    
        } catch (Exception e) {    
            e.printStackTrace();    
            throw new RuntimeException(e);    
        }    
    }    
}
Copy after login

简单实现Schedule的Quartz的例子


 第一步:引包

  要使用Quartz,必须要引入以下这几个包:

  1、log4j-1.2.16

  2、quartz-2.1.7

  3、slf4j-api-1.6.1.jar

  4、slf4j-log4j12-1.6.1.jar

  这些包都在下载的Quartz包里面包含着,因此没有必要为寻找这几个包而头疼。

  第二步:创建要被定执行的任务类

  这一步也很简单,只需要创建一个实现了org.quartz.Job接口的类,并实现这个接口的唯一一个方法execute(JobExecutionContext arg0) throws JobExecutionException即可。如:

import java.text.SimpleDateFormat;   
   
import java.util.Date;   
   
import org.quartz.Job;   
import org.quartz.JobExecutionContext;   
import org.quartz.JobExecutionException;   
   
public class myJob implements Job {   
   
    @Override   
    public void execute(JobExecutionContext arg0) throws JobExecutionException {   
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");   
        System.out.println(sdf.format(new Date()));   
    }   
   
}
Copy after login

第三步:创建任务调度,并执行

import java.text.SimpleDateFormat;  
import java.util.Date;  
  
import org.quartz.CronTrigger;  
import org.quartz.JobDetail;  
import org.quartz.Scheduler;  
import org.quartz.SchedulerFactory;  
import org.quartz.impl.StdSchedulerFactory;  
  
public class Test {  
    public void go() throws Exception {  
        // 首先,必需要取得一个Scheduler的引用  
        SchedulerFactory sf = new StdSchedulerFactory();  
        Scheduler sched = sf.getScheduler();  
        String time="0 51 11 ? * *";  
        // jobs可以在scheduled的sched.start()方法前被调用  
  
        // job 1将每隔20秒执行一次  
        JobDetail job = new JobDetail("job1", "group1", myJob.class);  
        CronTrigger trigger = new CronTrigger("trigger1", "group1");  
        trigger.setCronExpression(time);  
        Date ft = sched.scheduleJob(job, trigger);  
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");  
        System.out.println(  
                job.getKey() + " 已被安排执行于: " + sdf.format(ft) + ",并且以如下重复规则重复执行: " + trigger.getCronExpression());  
  
        // job 2将每2分钟执行一次(在该分钟的第15秒)  
        job = new JobDetail("job2", "group1",myJob.class);  
        trigger = new CronTrigger("trigger2", "group1");  
        trigger.setCronExpression(time);  
        ft = sched.scheduleJob(job, trigger);  
        System.out.println(  
                job.getKey() + " 已被安排执行于: " + sdf.format(ft) + ",并且以如下重复规则重复执行: " + trigger.getCronExpression());  
  
        // 开始执行,start()方法被调用后,计时器就开始工作,计时调度中允许放入N个Job  
        sched.start();  
        try {  
            // 主线程等待一分钟  
            Thread.sleep(60L * 1000L);  
        } catch (Exception e) {  
        }  
        // 关闭定时调度,定时器不再工作  
        sched.shutdown(true);  
    }  
  
    public static void main(String[] args) throws Exception {  
  
        Test test = new Test();  
        test.go();  
    }  
  
}
Copy after login



更多 java实现定时任务 Schedule相关文章请关注PHP中文网!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template