Building projects
Create a Springboot project, add @enablescheduling to its program entry, and start the dispatch task.
@SpringBootApplication @enableschedulingpublic class Springbootschedulingtasksapplication {public static void Main (string[] args) { springapplication.run (springbootschedulingtasksapplication.class, args);} }
Create a timed task
Create a timed task that prints the current time in the console every 5s.
@Componentpublic class Scheduledtasks { private static final Logger log = Loggerfactory.getlogger ( Scheduledtasks.class); private static final SimpleDateFormat DateFormat = new SimpleDateFormat ("HH:mm:ss"); @Scheduled (fixedrate =) public void Reportcurrenttime () { log.info ("The time was now {}", Dateformat.format ( New Date ()));} }
By adding @scheduled annotations to the method, it shows that the method is a dispatch task.
- @Scheduled (fixedrate = 5000): Executes 5 seconds after the last start point of execution
- @Scheduled (Fixeddelay = 5000): Executed 5 seconds after the last execution time
- @Scheduled (initialdelay=1000, fixedrate=5000): Executes after the first delay of 1 seconds, followed by fixedrate rules every 5 seconds
- @Scheduled (cron= "/5"): Define rules by cron expressions, what are CRO expressions, self-search engines.
Test
Start the Springboot project, the console has not been 5s to print out the current time.
2017-04-29 17:39:37.672 INFO 677-[pool-1-thread-1] com.forezp.task.ScheduledTasks:The time is now 17:39:37
2017-04-29 17:39:42.671 INFO 677-[pool-1-thread-1] com.forezp.task.ScheduledTasks:The time is now 17:39:42
2017-04-29 17:39:47.672 INFO 677-[pool-1-thread-1] com.forezp.task.ScheduledTasks:The time is now 17:39:47
2017-04-29 17:39:52.675 INFO 677-[pool-1-thread-1] com.forezp.task.ScheduledTasks:The time is now 17:39:52
Summarize
Creating a timed task in Springboot is simple and takes only 2 steps:
- 1. Add @enablescheduling annotations at the entrance of the program.
- 2. Add @scheduled annotations to the timing method.
Source Source
Enterprise Distribution Micro Service Cloud Springcloud springboot MyBatis (32) Spring boot do the dispatch task