难度:一颗星
1. Scheduled service
package com.schedule;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduledTaskService {
private static final SimpleDateFormat dateFormat =
new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000) // fixed rate
public void reportCurrentTime() {
System.out.println("Every 5s, show time: " + dateFormat.format(new Date()));
}
@Scheduled(cron = "0 28 11 ? * *") // fixed datetime
public void fixTimeExecution() {
System.out.println("At fixed time, show time: " + dateFormat.format(new Date()));
}
}
2. Enable Scheduling
package com.schedule;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@ComponentScan("com.schedule")
@EnableScheduling
public class ScheduledConfig {
}
3. Test
package com.schedule;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Bootrap {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ScheduledConfig.class);
// context.close(); //进行定时测试时,context不能关闭,否则看不出定时的效果。
}
}