Concise usage of Timer class in Java (1)

Source: Internet
Author: User
Tags dateformat

All types of Java applications generally require repeated tasks. Enterprise applications need to plan daily logs or evening batch processing. A j2se or j2se calendar application needs to schedule the alert time according to the user's conventions. However, the standard scheduling classes timer and timertask do not have enough flexibility to support the commonly needed scheduled task types. In this article, Java developer Tom White shows you how to build a simple and common planning framework to execute any complex planning tasks.

I will. util. timer and Java. util. timertask is collectively referred to as the Java timer framework, which enables programmers to easily plan simple tasks (note that these classes can also be used in j2s ). Before introducing this framework in Java 2 SDK, Standard Edition, and version 1.3, developers must write their own scheduling programs, which requires a lot of effort to process threads and complex objects. wait () method. However, the Java timer framework does not have enough capacity to meet the planning requirements of many applications. Even a task that needs to be executed repeatedly at the same time every day cannot be planned directly using timer, because a time jump occurs at the start and end of the Failover.

This article demonstrates a general timer and timertask planning framework that allows more flexible task scheduling. This framework is very simple-it includes two classes and one interface-and is easy to grasp. If you are used to using the Java timer framework, you should be able to quickly master this planning framework.

Schedule a single task

The planning framework is based on the Java timer framework class. Therefore, before explaining how to use the planning framework and how to implement it, we will first look at how to use these classes for planning.

Imagine an egg timer. After a few minutes (when the egg is ready), it will sound to remind you. The code in Listing 1 forms the basic structure of a simple egg timer, which is written in Java:

Listing 1. eggtimer class


     
      package org.tiling.scheduling.examples;import java.util.Timer;import java.util.TimerTask;public class EggTimer {    private final Timer timer = new Timer();    private final int minutes;    public EggTimer(int minutes) {        this.minutes = minutes;    }    public void start() {        timer.schedule(new TimerTask() {            public void run() {                playSound();                timer.cancel();            }            private void playSound() {                System.out.println("Your egg is ready!");                // Start a new thread to play a sound...            }        }, minutes * 60 * 1000);    }    public static void main(String[] args) {        EggTimer eggTimer = new EggTimer(2);        eggTimer.start();    }}
     

An eggtimer instance has a timer instance to provide necessary plans. After the egg timer is started using the START () method, It schedules a timertask and runs it after the specified minutes. When the time is up, Timer calls the START () method of timertask in the background, which will make it sound. The application stops when the timer is canceled.

Scheduled repeated tasks

By specifying a fixed execution frequency or a fixed execution interval, timer can schedule repetitive tasks. However, there are many applications that require more complex plans. For example, an alert clock that sends a wake-up ringtone at the same time every morning cannot simply use a fixed scheduled frequency of 86400000 milliseconds (24 hours ), it may be too late or too early to wake up when the clock is fast or slow (If your time zone uses clock. The solution is to use the calendar algorithm to calculate the next scheduled time of a daily event. This is exactly what the planning framework supports. Consider the alarmclock implementation in Listing 2:

Listing 2. alarmclock class


     
      package org.tiling.scheduling.examples;import java.text.SimpleDateFormat;import java.util.Date;import org.tiling.scheduling.Scheduler;import org.tiling.scheduling.SchedulerTask;import org.tiling.scheduling.examples.iterators.DailyIterator;public class AlarmClock {    private final Scheduler scheduler = new Scheduler();    private final SimpleDateFormat dateFormat =        new SimpleDateFormat("dd MMM yyyy HH:mm:ss.SSS");    private final int hourOfDay, minute, second;    public AlarmClock(int hourOfDay, int minute, int second) {        this.hourOfDay = hourOfDay;        this.minute = minute;        this.second = second;    }    public void start() {        scheduler.schedule(new SchedulerTask() {            public void run() {                soundAlarm();            }            private void soundAlarm() {                System.out.println("Wake up! " +                    "It's " + dateFormat.format(new Date()));                // Start a new thread to sound an alarm...            }        }, new DailyIterator(hourOfDay, minute, second));    }    public static void main(String[] args) {        AlarmClock alarmClock = new AlarmClock(7, 0, 0);        alarmClock.start();    }}
     

Note that this code is very similar to the egg timer application. The alarmclock instance has a schedmer (instead of a timer) instance to provide the necessary plans. After the alarm is triggered, the schedulertask (instead of the timertask) is scheduled to generate an alarm. This alarm is not to schedule a task to be executed after a fixed delay, but to describe its plan using the dailyiterator class. Here, it only schedules tasks to be executed at every morning. The following is an output under normal operation:


     
      Wake up! It's 24 Aug 2003 07:00:00.023Wake up! It's 25 Aug 2003 07:00:00.001Wake up! It's 26 Aug 2003 07:00:00.058Wake up! It's 27 Aug 2003 07:00:00.015Wake up! It's 28 Aug 2003 07:00:00.002...
     

Dailyiterator implements scheduleiterator, an interface that specifies the scheduled execution time of schedulertask as a series of Java. util. Date objects. Then, the next () method iterates the date object in chronological order. If the return value is null, the task will be canceled (that is, it will no longer run). In this case, an exception will be thrown when you try to plan again. Listing 3 contains the scheduleiterator interface:

Listing 3. scheduleiterator Interface


     
      package org.tiling.scheduling;import java.util.Date;public interface ScheduleIterator {    public Date next();}
     

The next () method of dailyiterator returns the date object of the same time every day (AM), as shown in Listing 4. Therefore, if you call next () for the new next () class, you will get the date that is passed to the constructor or am of the next day. If you call next () Again, the system will return the am of the next day, which is repeated. To implement this behavior, dailyiterator uses the java. util. Calendar instance. The constructor adds a day to the calendar. The setting of the Calendar Enables the first call of next () to return the correct date. Note that the Code does not explicitly mention the callback correction, because the calendar implementation (gregoriancalendar in this example) is responsible for processing this, so this is not required.

Listing 4. dailyiterator class


     
      package org.tiling.scheduling.examples.iterators;import org.tiling.scheduling.ScheduleIterator;import java.util.Calendar;import java.util.Date;/** * A DailyIterator class returns a sequence of dates on subsequent days * representing the same time each day. */public class DailyIterator implements ScheduleIterator {    private final int hourOfDay, minute, second;    private final Calendar calendar = Calendar.getInstance();    public DailyIterator(int hourOfDay, int minute, int second) {        this(hourOfDay, minute, second, new Date());    }    public DailyIterator(int hourOfDay, int minute, int second, Date date) {        this.hourOfDay = hourOfDay;        this.minute = minute;        this.second = second;        calendar.setTime(date);        calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);        calendar.set(Calendar.MINUTE, minute);        calendar.set(Calendar.SECOND, second);        calendar.set(Calendar.MILLISECOND, 0);        if (!calendar.getTime().before(date)) {            calendar.add(Calendar.DATE, -1);        }    }    public Date next() {        calendar.add(Calendar.DATE, 1);        return calendar.getTime();    }}
     

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.