A brief talk on Java timed task: TimerTask

Source: Internet
Author: User
Java timed Task TimerTask
Timing tasks have a variety of implementations, there are many open source on the web, the timing task framework can be referenced, but the blogger simply introduced the blogger to use the implementation of the four kinds of timing tasks: Timer and Timertaks, spring, quartz, spring and quartz. Not much to say, directly on the code
Timer and TimerTask

Let's take a look at the timer source first.

   public void Schedule (timertask task, Date Firsttime, long period) {
        if (period <= 0)
            throw new Illegalargumente Xception ("non-positive period.");
        Sched (Task, Firsttime.gettime (),-period);
    

Task is inherited from TimerTask custom tasks, Firsttime: First execution time period: execution cycle
Let's see how the timer is structured.

The timer provides four construction methods as an example public
 Timer (String name, Boolean Isdaemon) {
        thread.setname (name);
        Thread.setdaemon (Isdaemon);
        Thread.Start ();
    }

You can see that the timer is thread based and Isdaemon is set to daemon
Let's see what start is doing.

Public synchronized void Start () {
        //If the thread is already running, throw an exception if
        (threadstatus!= 0)
            throw new Illegalthreadstateexception ();
        Add this thread to the thread queue
        group.add (this);

        Boolean started = false;
        try {
            start0 ();
            started = true;
        } Finally {
            try {
                if (!started) {
                    group.threadstartfailed (this);
                }
            catch (Throwable ignore) {
            }
        }
    }
  However Start0 did not do anything, visible, start just put the thread into the thread queue
  private native void Start0 ();

However, the timer provides four different ways of doing it: construction methods, Shcedule, Cancel, purge

Back to the core method schedule, let's look at Sched:

 private void Sched (TimerTask task, long, long period) {if (Time < 0) throw new Illegalargume
        Ntexception ("Illegal Execution Time");

        if (Math.Abs (period) > (Long.max_value >> 1)) period >>= 1; Synchronized (queue) {if (!thread.newtasksmaybescheduled) throw new IllegalStateException ("Tim

            Er already cancelled. ");
                    Synchronized (Task.lock) {//If this thread throws an exception if it is initialized daily (task.state!= timertask.virgin)
                 throw new IllegalStateException ("Task already scheduled or cancelled");
                Next wake-up time task.nextexecutiontime = times;
                Task.period = period;
            Task.state = timertask.scheduled;
            ///Add the current thread to the queue tail queue.add (Task);
       If the wake thread is on the head, execute timertask if (queue.getmin () = Task) queue.notify (); }
    } 

A class that inherits TimerTask only needs its run method.

  @Override public
    Void Run () {
        System.out.println ("ScheduleTask Start: ++++++++++++++++");
    }

Initializing this class will start the task timer and Spring

Define the schedule of a call timer in a class method, and then initialize the method at spring startup

     The public void ExecuteTask () throws ParseException {
        //is executed once every 24 hours
        timer.schedule (
                new TimerTask () {
            @ Override public
            Void Run () {
                    System.out.println ("ScheduleTask Start: ++++++++++++++++");  StartTime, Dayspan);
    

Configuration file

<bean id= "ScheduleTask" class= "Com.task.ScheduleTask" init-method= "ExecuteTask" >
</bean>
TimerTask and Spring

Implement the Run method that inherits the TimerTask class, handing the dispatch task to spring

The public class ScheduleTask  extends timertask{
  @Override the public
    Void Run () {
        System.out.println (" ScheduleTask start: ++++++++++++++++ ");
    }

The configuration file is as follows:

  <bean id= "ScheduleTask" class= "Com.task.ScheduleTask" > </bean> <bean id= "Scheduledexecutorservice" class= "Org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean" > <property name= "awaitter
        Minationseconds "value="/> <property name= "Continuescheduledexecutionafterexception" value= "false"/> <property name= "Poolsize" value= "1"/> <property name= "Scheduledexecutortasks" >
        ;list> <ref bean= "Scheduledexecutortask"/> </list> </property> <property name= "Waitfortaskstocompleteonshutdown" value= "true"/> <property "name=" va lue= "1"/> </bean> <bean id= "Scheduledexecutortask" class= "Org.springframework.scheduling.concurren" T.scheduledexecutortask "> <!----> <property name=" Fixedrate "value=" true "when there are deferred tasks that modify task execution/&G
        T <propertyName= "Period" value= "1"/> <!--execute once per second--> <property name= "Timeunit" value= "milliseconds"/>  <!--specific tasks--> <property name= "runnable" ref= "ScheduleTask"/> </bean>

Here's a look at Fixedrate's source code.

protected void Registertasks (scheduledexecutortask[] tasks, Scheduledexecutorservice executor) {for
        ( Scheduledexecutortask task:tasks) {
            Runnable Runnable = getrunnabletoschedule (Task);
            if (Task.isonetimetask ()) {
                executor.schedule (runnable, Task.getdelay (), Task.gettimeunit ());
            else {
                if (task.isfixedrate ()) {
                    executor.scheduleatfixedrate (runnable, Task.getdelay (), Task.getperiod (), Task.gettimeunit ());
                }
                else {
                    Executor.schedulewithfixeddelay (runnable, Task.getdelay (), Task.getperiod (), Task.gettimeunit ());
            }
        }
    }

I can't see it anymore, I'll say it later.

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.