使用Cron安排任务,该任务允许动态更新 [英] Schedule a task with Cron which allows dynamic update

查看:138
本文介绍了使用Cron安排任务,该任务允许动态更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用sprint boot 1.3(春季版4.2)

I use sprint boot 1.3, spring 4.2

在这个班上

@Service
public class PaymentServiceImpl implements PaymentService {
    ....
    @Transactional
    @Override
    public void processPayment() {
        List<Payment> payments = paymentRepository.findDuePayment();
        processCreditCardPayment(payments);
    }
}

我想每x刻调用一次processPayment.

I would like to call processPayment every x moment.

此x力矩设置在数据库中. 用户可以对其进行修改.

This x moment is set in a database. The user can modify it.

所以我认为我不能使用注释.

So i think i can't use anotation.

我开始这个了

@EntityScan(basePackageClasses = {MyApp.class,     Jsr310JpaConverters.class})
@SpringBootApplication
@EnableCaching
@EnableScheduling
public class MyApp {

    @Autowired
    private DefaultConfigService defaultConfigService;

    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }

    @Bean
    public TaskScheduler poolScheduler() {
        SimpleAsyncTaskExecutor taskScheduler = new SimpleAsyncTaskExecutor();

        DefaultConfigDto defaultConfigDto = defaultConfigService.getByFieldName("payment-cron-task");
        String cronTabExpression = "0 0 4 * * ?";
        if (defaultConfigDto != null && !defaultConfigDto.getFieldValue().isEmpty()) {
            cronTabExpression = "0 0 4 * * ?";
        }

        appContext.getBean("scheduler");

        taskScheduler.schedule(task, new CronTrigger(cronTabExpression));
        return scheduler;
    }

也许这不是好方法.

有什么建议吗?

如果我需要创建类似这样的属性,则不知道是否可以获取我的上下文

Don't know if to get my context if i need to create a property like

@Autowired
ConfigurableApplicationContext context;

和之后的

public static void main(String[] args) {
        context = SpringApplication.run(MyApp.class, args);
}

推荐答案

看着这个问题似乎要更新调度程序,而无需重新启动.

Looking at the question seems like you want to update the scheduler, without restart.

您共享的代码仅确保从数据库中选择配置,但在不重新启动应用程序的情况下不会刷新.

The code you have shared only ensures the config is picked from DB, but it will not refresh without application restart.

以下代码将使用spring上下文中可用的默认调度程序,并根据数据库中可用的cron设置动态计算下一次执行时间:

The following code will use the default scheduler available in the spring context and dynamically compute the next execution time based on the available cron setting in the DB:

这是示例代码:

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

@SpringBootApplication
@EnableScheduling
public class Perses implements SchedulingConfigurer {
    private static final Logger log = LoggerFactory.getLogger(Perses.class);

    @Autowired
    private DefaultConfigService defaultConfigService;

    @Autowired
    private PaymentService paymentService;

    public static void main(String[] args) {
        SpringApplication.run(Perses.class, args);
    }

    private String cronConfig() {
        String cronTabExpression = "*/5 * * * * *";
        if (defaultConfigDto != null && !defaultConfigDto.getFieldValue().isEmpty()) {
            cronTabExpression = "0 0 4 * * ?";
        }
        return cronTabExpression;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                paymentService.processPayment();
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                String cron = cronConfig();
                log.info(cron);
                CronTrigger trigger = new CronTrigger(cron);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        });
    }
}

这篇关于使用Cron安排任务,该任务允许动态更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆