SpringBoot2.0使用自带的定时器

博客围绕Java定时任务展开,指出日常工作中定时任务常见,如定时发邮件、清除数据等。介绍了实现定时任务仅需两个步骤,即开启定时和编写任务调度的业务类,最后还提及要进行测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:日常工作中,我们难免会遇到许多定时任务,比如,定时发送邮件祝福用户生日快乐,某个时间定时清除某些数据

非常简单,就两个步骤就完事,

第一步:开启定时

第二步:编写任务调度的业务类

package com.itpengwei.idea.job.springbootjob.commer;

import com.itpengwei.idea.job.springbootjob.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

/**
 * @author 彭伟
 * @date 2018/8/27 16:07
 */
@Component
public class SchedulerTask {
    @Autowired
    private MailService mailService;
    @Value(value = "${mail.username.from}")
    private String username;

    @Scheduled(cron = "0/10 * * * * ? ")//cron表达式
    public void task() {
        String msg = "SpringBoot整合定时器发送邮件-----发送时间" + new SimpleDateFormat("HH:mm:ss").format(new Date());
        mailService.sendMail("发送者" + username + "----" + msg);
    }

    @Scheduled(cron = "0/5 * * * * ? ")
    public void task1() {
        String msg = "任务调度二-----发送时间" + new SimpleDateFormat("HH:mm:ss").format(new Date());
        mailService.sendMail("发送者---" + username + "----" + msg);
    }
}

没错,这就完事了,就是这么简单

接下来测试一下把:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值