Spring Task Scheduler
Starting with Spring3.1, the implementation of the scheduled task in spring becomes unusually simple. First, the support for the scheduled task is opened by configuring the class annotation @enablescheduling.
Then annotate @scheduled on the method that you want to perform the scheduled task, declaring that this is a scheduled task.
Spring supports many types of scheduled tasks through @scheduled, including Cron, Fixdelay, fixrate, and more.
Instance
1. Schedule the task execution class.
Package Com.wisely.highlight_spring4.ch3.taskscheduler;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Importorg.springframework.scheduling.annotation.Scheduled;
ImportOrg.springframework.stereotype.Service;
@Service
public class Scheduledtaskservice {
private static Final SimpleDateFormatDateFormat =New SimpleDateFormat ("HH:mm:ss");
@Scheduled (fixedrate =5000)1
public void Reportcurrenttime () {
System.Out.println ( "executes" + dateformat.format (new Date ()));
}
@Scheduled (cron = "0 28 11? * * ") //2
public void Fixtimeexecution () {
System.out.println ( "at the specified time" + dateformat.format (new Date ()) + "Implementation");
}
}
Code explanation
By @scheduled, this method is a scheduled task that is executed every fixed time using the Fixedrate property.
The cron attribute can be performed at a specified time, in this case, 11:28 per day; Cron is a scheduled task under Unix and UNIX (Linux) systems.
The configuration class.
Package Com.wisely.highlight_spring4.ch3.taskscheduler;
Import Org.springframework.context.annotation.ComponentScan;
Import org.springframework.context.annotation.Configuration;
Import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@ComponentScan ("Com.wisely.highlight_spring4.ch3.taskscheduler")
@EnableScheduling //1
public class Taskschedulerconfig {
}
Code explanation
Open support for scheduled tasks with @enablescheduling annotations.
Run
Package Com.wisely.highlight_spring4.ch3.taskscheduler;
Import Org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void Main (string[] args) {
Annotationconfigapplicationcontext context =
New Annotationconfigapplicationcontext (Taskschedulerconfig. Class);
}
}
Spring Task Scheduler