task定时任务

Spring 实现 SchedulingConfigurer 接口完成动态定时任务(配合数据库动态执行)

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;
 
import java.time.LocalDateTime;
 
@Configuration
@EnableScheduling
public class CompleteScheduleConfig implements SchedulingConfigurer {
 
    @Mapper
    public interface CronMapper {
        @Select("select cron from cron limit 1")
        String getCron();
    }
 
    @Autowired
    @SuppressWarnings("all")
    CronMapper cronMapper;
 
    /**
     * 执行定时任务.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () -> System.out.println("执行定时任务2: " + LocalDateTime.now().toLocalTime()),
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    //2.1 从数据库获取执行周期
                    String cron = cronMapper.getCron();
                    //2.2 合法性校验.
                    if (StringUtils.isEmpty(cron)) {
                        // Omitted Code ..
                    }
                    //2.3 返回执行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }
 
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringTask是Spring框架提供的一个用于实现定时任务的模块。它可以帮助开发者在应用中创建、调度和管理定时任务。 要使用SpringTask,首先需要在Spring配置文件中配置一个任务调度器。可以使用`@EnableScheduling`注解来启用SpringTask,并且在需要执行定时任务的方法上使用`@Scheduled`注解来指定任务的触发条件。 例如,下面的代码展示了一个简单的定时任务配置: ```java import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component @EnableScheduling public class MyTask { @Scheduled(fixedRate = 5000) // 每隔5秒执行一次任务 public void myTask() { // 执行定时任务的逻辑代码 System.out.println("定时任务执行中..."); } } ``` 在上述代码中,使用`@Component`注解将`MyTask`类注册为Spring的组件,并使用`@EnableScheduling`注解启用SpringTask。然后,在`myTask()`方法上使用`@Scheduled`注解指定了定时任务的触发条件,这里是每隔5秒执行一次。 通过以上配置,当应用启动后,定时任务就会按照指定的触发条件自动执行。 除了`fixedRate`之外,`@Scheduled`注解还支持其他的触发条件配置,如`fixedDelay`、`cron`等,开发者可以根据具体需求选择合适的触发条件。 希望以上内容对你有帮助,如果还有其他问题,请随时提出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值