Spring timer TimerTask usage:
When the tomcat service is started, the spring timer container will execute the tasks in the timer when loading. You can set the time interval and delay for execution. The specific steps are as follows:
Timer java code:
Package com. coalmine. desktop;
Import java. text. ParseException;
Import java. text. SimpleDateFormat;
Import java. util. Date;
Import java. util. TimerTask;
Public class Task extends TimerTask {
@ Override
// Timer entry. run () contains your task job.
Public void run (){
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss ");
Date date = new Date ();
System. out. println (sdf. format (date) + "execute the TimerTask timer ================ ");
}
}
The applicationContext. xml configuration is as follows:
<! -- Spring scheduled task configuration -->
<Bean id = "scheduled Task" class = "com. coalmine. desktop. Task"> </bean>
<Bean id = "scheduledTask"
Class = "org. springframework. scheduling. timer. ScheduledTimerTask">
<Property name = "timerTask">
<Ref bean = "Processing Task"/>
</Property>
<! -- Task execution cycle 5S (in milliseconds) -->
<Property name = "period">
<Value> 5000 </value>
</Property>
<! -- Task execution latency of 10 s -->
<Property name = "delay">
<Value> 10000 </value>
</Property>
</Bean>
<! -- Start the timer -->
<Bean id = "timerBean"
Class = "org. springframework. scheduling. timer. TimerFactoryBean">
<Property name = "scheduledTimerTasks">
<List>
<Ref bean = "scheduledTask"/>
</List>
</Property>
</Bean>
OK, that's simple. After the service is started, the timer is loaded. after a delay of 10 seconds, run () every five seconds ()