1. Example of use
1. Create a java project and introduce spring-related jar packages (omitted)
2. Add the following configuration to the spring configuration file:
<task:annotation-driven/>
<context:component-scan base-package="com.tuozixuan.task"/>
3. Write the following sample code and run
package com.tuozixuan.task; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component("myTask") public class MyTask { @Scheduled(cron="0 0/5 10-12 * * ?") public void execute() { String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); System.out.println("[" + date + "]execute task..."); } public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring.xml"}); } }
2. Detailed explanation of spring timing tasks
1. @Scheduled configuration
@Scheduled(fixedRate=1000), fixedRate indicates that this method needs to be called periodically every specified number of milliseconds.
@Scheduled(fixedDelay=2000), fixedDelay is used to specify the interval between method calls (the interval between the completion of one call and the start of the next call).
@Scheduled(cron="0 0/5 10-12 * * ?") cron is used to specify when this method is called.
cron settings:
1) Seconds (0-59)
2) Minutes (0-59)
3) Hours (0-23)
4) Day of the month (0-31)
5) Month (1-12 or JAN-DEC)
6) Day of the week (1-7 or SUN-SAT)
7) Year (1970-2099)
Each element can be explicitly specified as a value (such as 3), a range ( such as 2-5), a list ( such as 2,4,7), or a wildcard (such as *).
The day of the month summary and the day of the week are mutually exclusive, you can set a question mark (?) to indicate which field you do not want to set
3. Asynchronous method
1. Annotate the bean method with @Async to make the method an asynchronous execution method. The code example is as follows:
package com.tuozixuan.task; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @Component("myTask") public class MyTask { @Async public void executeAsync() { System.out.println("async execute task start..."); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace (); } System.out.println("async execute task end..."); } public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring.xml"}); MyTask myTask = context.getBean("myTask", MyTask.class); myTask.executeAsync(); System.out.println("main..."); } }