在spring boot中写定时任务很简单,两个注解就可以实现。在启动类中加@EnableScheduling ,然后在你需要定时的方法上加上@Scheduled(cron="0 10 8 * * ?");括号内为cron表达式。如下图:
接收邮件及其判断是否有附件,并且存储附件。
public class TimerTaskServiceImpl implements TimerTaskService {
@Autowired
private ParseTxtServiceImpl parseTxtService;
/**
* 接收邮件
*/
@Override
@Scheduled(cron="0 10 8 * * ?")
public void timerTaskInfo(){
//邮件配置信息
String host=Constants.MAIL_HOST;
String userName=Constants.MAIL_USER_NAME;
String passWord=Constants.MAIL_PASS_WORD;
//邮件配置类
Properties properties=new Properties();
//邮件配置缓存
Session session=Session.getDefaultInstance(properties);
session.setDebug(true);
String fileName=null;
try {
//邮件服务器的类型
Store store = session.getStore("pop3");
//连接邮箱服务器
store.connect(host,userName,passWord);
// 获得用户的邮件帐户
Folder folder=store.getFolder("INBOX");
if (folder == null) {
logger.info("获取邮箱文件信息为空");
}
// 设置对邮件帐户的访问权限可以读写
folder.open(Folder.READ_WRITE);
Calendar calendar=Cal