1, Application.properties
#cronjob. EVERYSECOND.CRON=0/1 * * * * * *JOB.EVERYTENSECOND.CRON=0/10 * * * * * *job.everyminute.cron=0 0/1 * * * *job.everyse cond2.cron=* 0/1 * * * *
Note: Cron expressions
- First: Per second
- Second one: every 10 seconds
- The third one: every Minute
- Fourth one: Per second ( Note that this is not per minute )
2, Cronjobtest.java
1 PackageCom.xxx.secondboot.cron;2 3 Importjava.util.Date;4 5 Importorg.apache.commons.lang3.time.DateFormatUtils;6 Importorg.springframework.context.annotation.Configuration;7 Importorg.springframework.scheduling.annotation.Scheduled;8 Importorg.springframework.stereotype.Component;9 Ten /** One * Cron Test A */ - //@Configuration - @Component the Public classCronjobtest { - - inti = 0; - +@Scheduled (cron = "${job.everysecond.cron}") - Public voidEverysecond () { +System.out.println ("First" + (++i) + "call, task per second, current time:" +nowtime ()); A } at - PrivateString Nowtime () { - returnDateformatutils.format (NewDate (), "Yyyy-mm-dd HH:mm:ss"); - } -}
3. Application.java (Startup Class)
At this point, start boot and you will notice that the scheduled task is not executed and you need to add an annotation. As follows:
1 PackageCom.xxx.secondboot;2 3 Importorg.springframework.boot.SpringApplication;4 Importorg.springframework.boot.autoconfigure.SpringBootApplication;5 Importorg.springframework.scheduling.annotation.EnableScheduling;6 7 ImportSpringfox.documentation.swagger2.annotations.EnableSwagger2;8 9 @SpringBootApplicationTen @EnableSwagger2 One @EnableScheduling A Public classApplication { - Public Static voidMain (string[] args) { -Springapplication.run (Application.class, args); the } -}
Note: Be sure to add @enablescheduling on the Startup class to start the scheduled task , otherwise the scheduled task will not work!!!
Test:
Start the service and view the console output!!!
21st Chapter Springboot + Scheduled Tasks