准备定时任务
@Scheduled 标明方法什么时候执行
package com.mcs.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduleService {
@Autowired
JavaMailSenderImpl mailSender;
// cron表达式
@Scheduled(cron = "*/30 * * * * ?")
public void hello() {
System.out.println("被执行了");
}
}
cron:计划任务,是任务在约定的时间执行已经计划好的工作
cron表达式不会写可直接百度查cron在线生成器
开启定时任务
@EnableScheduling开启定时任务
package com.mcs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
//开启定时功能
@EnableScheduling
public class SpringbootstudyApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootstudyApplication.class, args);
}
}