[Java] detailed explanation of source code for Java scheduled tasks

Source: Internet
Author: User
Tags time in milliseconds

I found it online. There are many methods for writing scheduled tasks in Java, and many frameworks provide scheduled task interfaces. For beginners of Java programmers, it is better to consider the content in JDK.

First look at the principle:

In JDK, the execution of timer tasks requires two basic classes:
Java. util. timer;
Java. util. timertask;
 
To run a scheduled task, follow these steps:
1. Create a timertask to be executed.
2. Create a timer instance and add timertask to the timer using the schedule () method provided by timer. Set the execution rules at the same time.
 
After the timer initialization code is executed, the timer scheduled task is executed according to the settings.
 
The schedule () method in timer has multiple reload formats to adapt to different situations. The format of this method is as follows:
Void schedule (timertask task, date time)
Schedule the task to be executed at the specified time.
Void schedule (timertask task, date firsttime, long period)
Schedule the specified task to start repeated fixed delay execution at the specified time.
Void schedule (timertask task, long delay)
Schedule the task to be executed after the specified delay.
Void schedule (timertask task, long delay, long period)
Schedule the specified task to start repeated fixed delays after the specified delay.
 
Timer is thread-safe. It can be extended to a large number of tasks simultaneously arranged (there are thousands of tasks with no problems ). All of its constructor Methods start the timer thread. You can call cancel () to terminate this timer and discard all tasks currently scheduled. Purge () removes all canceled tasks from the timer's task queue. This class does not provide real-time guarantee: it uses the object. Wait (long) method to schedule tasks.
 
Timertask is an abstract class, which is scheduled by timer to be executed at one time or repeatedly. It has an abstract method run () ---- the operation to be performed by the timer task. Therefore, each specific task class must inherit the timertask class and override the run () method. There are also two non-Abstract METHODS:
Boolean cancel ()
Cancel this timer task.
Long scheduledexecutiontime ()

Returns the scheduled execution time of the task.

Let's look at the source code:

Package Nov; import Java. util. date; import Java. util. timer; import Java. util. timertask;/***** <p> * Title: scheduled task test code/P> ** <p> * description: example business class * </P> ** <p> * copyright: Copyright (c) 2012 * </P> *** @ author DML @ 2012-11-29 * @ version 1.0 */public class timertest extends timertask {/*** the operation that the timer task will perform. */Public void run () {date executetime = new date (this. scheduledexecutiontime (); system. out. println ("the task execution time is" + executetime);} public static void main (string [] ARGs) {timer = new timer (); timertask task = new timertest (); timer. schedule (task, 500l, 1000l );}}

Execution result:

The execution time of this task is Thu Nov 29 10:39:38 CST 2012. The execution time of this task is Thu Nov 29 10:39:39 CST 2012. The execution time of this task is Thu Nov 29 10:39:40 CST 2012. the time is Thu Nov 29 10:39:41 CST 2012 the execution time of this task is Thu Nov 29 10:39:42 CST 2012 the execution time of this task is Thu Nov 29 10:39:43 CST 2012 the execution time of this task is Thu Nov 29 10:39:44 CST 2012 the execution time of this task is Thu Nov 29 10:39:45 CST 2012 the execution time of this task is Thu Nov 29 10:39:46 CST 2012 the execution time of this task is Thu Nov 29 10:39:47 CST 2012 the task is executed on Thu Nov 29. 10:39:48 CST 2012 the execution time of this task is Thu Nov 29 10:39:49 CST 2012 the execution time of this task is Thu Nov 29 10:39:50 CST 2012 the execution time of this task is Thu Nov 29 10:39:51 CST 2012 this time the task execution time is Thu Nov 29 10:39:52 CST 2012. The task execution time is Thu Nov 29 10:39:53 CST 2012. The task execution time is Thu Nov 29 10:39:54 CST 2012. thu Nov 29 10:39:55 CST 2012 the time for executing this task is Thu Nov 29 10:39:56 CST 2012 the time for executing this task is Thu Nov 29 10:39:57 CST 2012 the time for executing this task is Thu Nov 29 10:39:58 CST 2012 this assignment The task execution time is Thu Nov 29 10:39:59 CST 2012 ......

Analysis:

The preceding example calls the following method:

    /**     * Schedules the specified task for repeated <i>fixed-delay execution</i>,     * beginning after the specified delay.  Subsequent executions take place     * at approximately regular intervals separated by the specified period.     *     * <p>In fixed-delay execution, each execution is scheduled relative to     * the actual execution time of the previous execution.  If an execution     * is delayed for any reason (such as garbage collection or other     * background activity), subsequent executions will be delayed as well.     * In the long run, the frequency of execution will generally be slightly     * lower than the reciprocal of the specified period (assuming the system     * clock underlying <tt>Object.wait(long)</tt> is accurate).     *     * <p>Fixed-delay execution is appropriate for recurring activities     * that require "smoothness."  In other words, it is appropriate for     * activities where it is more important to keep the frequency accurate     * in the short run than in the long run.  This includes most animation     * tasks, such as blinking a cursor at regular intervals.  It also includes     * tasks wherein regular activity is performed in response to human     * input, such as automatically repeating a character as long as a key     * is held down.     *     * @param task   task to be scheduled.     * @param delay  delay in milliseconds before task is to be executed.     * @param period time in milliseconds between successive task executions.     * @throws IllegalArgumentException if <tt>delay</tt> is negative, or     *         <tt>delay + System.currentTimeMillis()</tt> is negative.     * @throws IllegalStateException if task was already scheduled or     *         cancelled, timer was cancelled, or timer thread terminated.     */    public void schedule(TimerTask task, long delay, long period) {        if (delay < 0)            throw new IllegalArgumentException("Negative delay.");        if (period <= 0)            throw new IllegalArgumentException("Non-positive period.");        sched(task, System.currentTimeMillis()+delay, -period);    }

Three parameters: continuous task delay period

Call the sched method after the time is set properly:

    /**     * Schedule the specified timer task for execution at the specified     * time with the specified period, in milliseconds.  If period is     * positive, the task is scheduled for repeated execution; if period is     * zero, the task is scheduled for one-time execution. Time is specified     * in Date.getTime() format.  This method checks timer state, task state,     * and initial execution time, but not period.     *     * @throws IllegalArgumentException if <tt>time()</tt> is negative.     * @throws IllegalStateException if task was already scheduled or     *         cancelled, timer was cancelled, or timer thread terminated.     */    private void sched(TimerTask task, long time, long period) {        if (time < 0)            throw new IllegalArgumentException("Illegal execution time.");        synchronized(queue) {            if (!thread.newTasksMayBeScheduled)                throw new IllegalStateException("Timer already cancelled.");            synchronized(task.lock) {                if (task.state != TimerTask.VIRGIN)                    throw new IllegalStateException(                        "Task already scheduled or cancelled");                task.nextExecutionTime = time;                task.period = period;                task.state = TimerTask.SCHEDULED;            }            queue.add(task);            if (queue.getMin() == task)                queue.notify();        }    }

Synchronized modifier to ensure thread security... there are many other methods in the Timer class. Try again when you are free.

P.s. It is important to read the code in JDK frequently to help develop a good code annotation style.

Dml@2012.11.29

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.