Spring annotation @EnableScheduling scheduled task annotation

To implement scheduled tasks, first enable support for scheduled tasks by annotating @EnableScheduling in the configuration class.

Then annotate @Scheduled on the method to execute the scheduled task, declaring that this is a scheduled task

Example: Scheduled Task Execution Class

The methods in this class need the @Scheduled annotation to be used with @EnableScheduling.

package cn.hncu.p3.p3_taskscheduler;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User:
 * Date: 2016/11/22.
 * Time: 10:25 pm.
 * Explain: Scheduled task execution class
 */
@Service
public class ScheduledTaskService {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000) // Declare this method as a scheduled task through @Scheduled, and use the fixedRate property to execute 
    public  void reportCurrentTime(){
        System.out.println( "Execute every 5 seconds"+dateFormat.format( new Date()));
    }

    @Scheduled(cron = "0 07 20 ? * *" ) // Use the cron attribute to execute at the specified time, this example refers to the execution at 20:07 every day;
     // cron is under UNIX and UNIX-like (Linux) systems The timed task 
    public  void fixTimeExecution(){
        System.out.println( "At the specified time"+dateFormat.format( new Date())+"Execute" );
    }
}

configuration class

Enable support for scheduled tasks via the @EnableScheduling annotation

package cn.hncu.p3.p3_taskscheduler;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * Created with IntelliJ IDEA.
 * User:
 * Date: 2016/11/22.
 * Time: 10:32 pm.
 * Explain: Configuration class
 */

@Configuration
@ComponentScan("cn.hncu.p3.p3_taskscheduler")
@EnableScheduling // Enable support for scheduled tasks through the @EnableScheduling annotation 
public  class TaskScheduleConfig {
}

运行结果

package cn.hncu.p3.p3_taskscheduler;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Created with IntelliJ IDEA.
 * User:
 * Date: 2016/11/22.
 * Time: 10:34 pm.
 * Explain: Running class
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskScheduleConfig.class);
    }
}

operation result

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325883728&siteId=291194637