The easy way is to use an annotation-based (@scheduled) method.
  1. Add annotations to the SpringBoot boot class

@enablescheduling Starts a scheduled task

  1. The implementation class adds annotations

@Component is used to tag configuration classes and has the effect of Component.

  1. Implementation methods add annotations
// The @scheduled (crON = "${ims.sync.corn-expression}") public void syncFolderJob() throws InterruptedException { String[] appCodeArr = appCodes.split(","); for (String appCode : appCodeArr) { long startTime = System.currentTimeMillis(); Future<String> taskSyncFolder = FolderService. syncFolder(appCode); if(taskSyncFolder.isDone()) { break; } Thread.sleep(1000); long endTime = System.currentTimeMillis(); Calendar c = calendar.getInstance (); c.setTimeInMillis(endTime - startTime); Log.info (" application: "+ appCode +" Execution end, time: "+ c.et (calendar.minute) +" MINUTE "+ c.et (calendar.second) +" SECOND "); }}Copy the code

@scheduled In addition to flexible parameter expressions cron, @scheduled also supports simple delay operations, such as fixedDelay, fixedRate fill in the corresponding number of milliseconds.

Here I am configuring the corn execution time in application.yml.

The Cron expression parameters represent:

Seconds (0 to 59) For example, 0/5 indicates every 5 seconds

Points (0 ~ 59)

When (0 ~ 23)

The value is in the range of 0 to 31

Month (0 ~ 11)

A few weeks (1-7 or SUN/MON/TUE/WED/THU FRI/SAT)

Corn online generation address: cron.qqe2.com

Multithreaded enable scheduled task method:
  1. Add annotations to the start class

@EnableAsyncEnable multi-threaded annotations

  1. Implementation classes and implementation methods add annotations
@Component @EnableScheduling // 1. Public class SyncFolderScheduled {@async@scheduled (fixedDelay = 1000) // The interval is 1 second public Void first() throws InterruptedException {system.out.println (" The first scheduled task starts: "+ localDateTime.now ().tolocalTime () + "\r\n Thread:" + Thread.currentThread().getName()); System.out.println(); Thread.sleep(1000 * 10); } @async@scheduled (fixedDelay = Scheduled) public void second() {system.out.println (" the second Scheduled task has started: "+ localDateTime.now ().tolocalTime () + "\r\n Thread:" + Thread.currentThread().getName()); System.out.println(); }}Copy the code

Thanks for watching. If there is something wrong, please advise.