Simple use of Timer class in Java language (1)

xiaoxiao2021-03-06  126

All types of Java applications generally need to programs duplicate tasks. Enterprise applications need to plan a daily log or evening batch process. A J2SE or J2ME calendar application needs to be alarm time according to the user's conventions. However, standard scheduling Timer and Timertask do not have sufficient flexibility and cannot support typically required planned tasks. In this article, Java Developers Tom White show you how to build a simple and universal planning framework for performing any complex planning tasks.

I will collect java.util.timer and java.util.timertask as the Java timer framework, which makes programmers to plan simple tasks (note that these classes can also be used in J2ME). Prior to the introduction of this framework in Java 2 SDK, Standard Edition, Version 1.3, developers must write their own schedule, which requires a lot of energy to handle threads and complex object.wait () methods. However, the Java timer framework does not have enough capabilities to meet the planning requirements of many applications. Even a task that needs to be executed at the same time every day, and you can't use Timer to plan it directly because time jump occurs during the daylight saving time and end. This article shows a universal Timer and Timertask plan framework to allow more flexible planning tasks. This framework is very simple - it includes two classes and an interface - and is easy to master. If you are accustomed to using the Java Timer Frame, you should be able to master this plan framework quickly. Planning a single task plan framework is based on the Java timer framework class. Therefore, in explaining how to use a plan framework and how to implement it, we will first see how to plan these classes. Imagine a cooking egg timer, after a few minutes (this time the egg is boiled) it will make a sound reminder you. The code in Listing 1 forms a simple basic structure of the egg timer, which writes in Java language: List 1. Eggtimer class

Package org.tiling.scheduling.examples;

Import java.util.timer;

Import java.util.timertask;

Public class eviM {

PRIVATE FINAL 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 Plays () {

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 ();

}

}

The EggTimer instance has a Timer instance for providing the necessary plans. After starting the boiled egg timer with the start () method, it plans a Timertask, executed after the specified number of minutes. Time is here, Timer calls Timertask's Start () method in the background, which will make it sound. This application will abort after canceling the timer. Plan repeated task

The Timer can plan a repeated task by specifying a fixed execution frequency or a fixed execution time interval. However, there are many applications to require more complex plans. For example, a alarm clock that is called awakening alert alarm every morning cannot simply use the fixed planning frequency of 86400,000 milliseconds (24 hours), because in those days that are fast or slower (if your time zone uses Summer time), Wake up may be late or too early. The solution is to use the calendar algorithm to calculate the time of the next plan. And this is supported by the plan frame. 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.dailyItem;

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 special) {

THIS.HOFDAY = HOUROFDAY;

THIS.MINUTE = Minute;

THIS.SECOND = SECOND;

}

Public void start () {

Scheduler.schedule (New Schedulertask () {

Public void run () {

SoundAlarm ();

}

Private vid 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 this code is very similar to the egg timer application. The AlarmClock instance has a Scheduler instance for providing the necessary plans. This alarm is scheduled to schedule SCHEDULERTASK (not Timertask) to issue alarm. This alarm is not executed after a task is executed after a fixed delay time, but is used to describe its plan with a DailyItemrator class. Here, it is just a planned task performed at 7:00 am every day. Below is an output in normal operation: Wake Up! It's 24 Aug 2003 07: 00:00.023

Wake Up! It's 25 Aug 2003 07: 00: 00.001

Wake Up! It's 26 Aug 2003 07: 00: 00.058

Wake Up! It's 27 Aug 2003 07: 00: 00.015

Wake Up! It's 28 Aug 2003 07: 00: 00.002

...

DAILYITERATOR implemented ScheduleITerator, which is an interface to a series of java.util.date objects to a series of java.util.date objects. Then the next () method iterates the DATE object in order. Return Value NULL will cause task to cancel (ie, it will never run) - this, trying to play an exception 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 ();

}

DAILYITERATOR's next () method returns a DATE object that represents the same time (7:00 am), as shown in Listing 4. So, if next () is called next (), you will get 7:00 AM on the day or after the date of passing to the constructor. Call next () will return 7:00 AM a day, so repeated. In order to achieve this behavior, DailyItemrator uses the Java.util.Calendar instance. The constructor will add one day in the calendar, which makes the first call next () returns the correct Date. Note The code is not explicitly referred to the summertime correction because the Calendar implementation (GregorianCalendar in this case is responsible for processing this, so don't do this.

Listing 4. DailyIterator class

Package org.tiling.scheduling.examples.Item;

Import org.tiling.scheduling.scheduleiterator;

Import java.util.calendar;

Import java.util.date;

/ **

* A Dailyiterator Class Returns a sequence of dates on subsequent days

* Repesenting The Same Time Each Day.

* /

Public class DailyItemrator Implements ScheduleITer {

Private final int hourofday, minute, second;

PRIVATE FINAL.GETARENDAR = Calendar.GetInstance (); Public DailyIterator (int.com) {

THIS (HourofDay, Minute, Second, New Date ());

}

Public DailyITerator (int HourofDay, int minute, int standard, date date) {

THIS.HOFDAY = 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 ();

}

}

转载请注明原文地址:https://www.9cbs.com/read-127017.html

New Post(0)