Java - How to implement TIMER functionality

xiaoxiao2021-03-06  50

Java - How to implement TIMER functionality

2004-11-8

Author: meanson wang

Email: meansonw@hotmail.com

Date: 2004-11-8

Java To achieve schedule management [Perform a task every day or monthly], you can use Timer and Timertask. This article describes how to implement a schedule.

Here, two classes are designed, one listening class, which is used to perform tasks [can perform multiple tasks]. A task class, used to call tasks. Here is 15:00 per day to perform a task .1.Listener ClassPackage Timer ; import java.util.TimerTask; import java.util.Timer; import javax.servlet *;. public class RemindListener implements ServletContextListener {private java.util.Timer timer = null; public void contextInitialized (ServletContextEvent sce) {timer = new java .util.timer (TRUE); SCE.GetServletContext (). log (new java.util.date () "Timer Start Up!"); Timer.Schedule (New Remindtask (), 0,60 * 60 * 1000) ; // every 60 minute rollsce.getServletContext () log (new java.util.Date () "Schedule loaded!");.} public void contextDestroyed (ServletContextEvent sce) {timer.cancel (); sce.getServletContext () .log (new java.util.Date () "Timer destroyed!");}} 2.Task classpackage timer; import java.util.TimerTask; import java.util.Calendar; public class RemindTask extends TimerTask {private static final INT C_SCHEDULE_HOUR = 15; private static boolean isrunning = false; public remindtask () {} public void run () {Calendar Cal = Calendar.Get Instance (); if (! Isrunning) {if (c_schedule_Hour == Cal.get (Calendar.Hour_Of_Day)) {isrunning = true; system.out.println (new java.util.date () "task start"); // Todo for example INT i = 0; While (i <10) {system.out.println (new java.util.date () "DONE! TASK" i "/" 10);} isrunning = False; system.out.println (new java.util.date () "all task done!");

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

New Post(0)