Spring Timer technology Terminator -- Implement Spring timer using Scheduled Annotation
There are two ways to implement the timer function in Spring: Scheduled annotation mode and XML configuration mode, this blog introduces how to use Scheduled annotation in Spring to implement the timer function. The code and corresponding explanations are as follows:
Code 1-Spring configuration file (applicationContext. xml file ):
Note: Pay attention to the six lines of code 05th, 11, 12, 21, 23, and 25 in the above Code.
Code 2 -- Spring timer test class (SpringTimerTest. java file ):
Package com. ghj. packageoftimer; import java. text. simpleDateFormat; import java. util. date; import org. springframework. scheduling. annotation. scheduled; import org. springframework. stereotype. component; /*** Spring timer test class ** @ author Gao huanjie */@ Component // This class completes bean creation and automatic dependency injection public class SpringTimerTest {/*** Spring timer Test method ** @ author Gao huanjie */@ Scheduled (cron = 0 0/1 ***?) // Use the @ Scheduled annotation to define this method as a Spring Scheduled call method. cron is used to specify the time when the method is called. public void test () {System. err. println (new SimpleDateFormat (MM mm dd, yyyy hh mm ss seconds ). format (new Date ()));}}
Code 3 -- load the Spring configuration file and start the Spring timer class (StartSpringTimer. java file ):
Package com. ghj. packageoftest; import org. springframework. context. support. classPathXmlApplicationContext;/*** load the Spring configuration file and start the Spring timer ** @ author Gao huanjie */public class StartSpringTimer {public static void main (String [] args) {new ClassPathXmlApplicationContext (conf/spring/applicationContext. xml); System. out. println (after loading the Spring configuration file, the Spring timer is started successfully !!!);}}
Advantages of Spring timer implementation in this way:
In this way, the timer function is my favorite, this method is simple and flexible-you only need to add Scheduled comments to the methods that have been loaded into the Spring container class and specify the time for this method.
Q &:
If you are interested, you may have the following questions: Is there any special requirement on the access permission of the Scheduled annotated method when using the Spring timer implemented in this way, there are no special requirements for this. You can define this method as private, so that this method will not be exposed.