简体   繁体   English

如何在春季通过个人资料启用@Scheduled 工作?

[英]How to enable @Scheduled jobs by profile in spring?

How could I enabled scheduled jobs only in specific profiles?如何仅在特定配置文件中启用计划作业?

pseudocode:伪代码:

@Scheduled(cron = "${job.cron}")
@Profile("prod")
public void runJob() {

}

Is that possible?那可能吗?

You should have one bean per profile:每个配置文件应该有一个 bean:

@Component
@Profile("prod")
public class ProdJob {

    @Scheduled(cron = "${job.cron}")
    public void runJob() {

    }

}

@Component
@Profile("beta")
public class BetaJob {

    @Scheduled(cron = "${job.cron}")
    public void runJob() {

    }
}

You can do it using following approach.您可以使用以下方法来完成。 Almost as you already did, but add colon and then the default value that should be picked if property not found.几乎和你已经做的一样,但添加冒号,然后添加默认值,如果未找到属性,则应选择该值。 Here we use '-' as cron disable expression:这里我们使用“-”作为 cron 禁用表达式:

@Scheduled(cron = "${job.cron:-}")
public void runJob() {

}

Then define cron expression in desired profile (for example using properties file).然后在所需的配置文件中定义 cron 表达式(例如使用属性文件)。

Here is the application-prod.properties content:这是 application-prod.properties 的内容:

job.cron=*/30 * * * * *

Here for prod profile it will be launched every 30 seconds and for all others it is turned off.对于 prod 配置文件,它将每 30 秒启动一次,而对于所有其他配置,它将关闭。

I use spring boot version 2.3.7 and the solution to this problem is equal to the pseudocode you provided.我用的是spring boot 2.3.7版本,这个问题的解决方法和你提供的伪代码一样。 You inspired their team :-).你激励了他们的团队:-)。

// Enable sceduling
@Configuration
@EnableScheduling
public class SchedulerConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

        threadPoolTaskScheduler.setPoolSize(5);
        threadPoolTaskScheduler.setThreadNamePrefix("my.main.package-Scheduler-");
        threadPoolTaskScheduler.initialize();

        scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
    }
}

// A scheduled job that runs only when profile "prod" is enabled
@Component
@Profile("prod")
@NoArgsConstructor
class ExpirationNotificationScheduler {

    // Just for test, run each 10th second or each minute
    @Scheduled(cron = "10 * * * * *") // second, minute, hour, day of month, month, day(s) of week
    public void notifyExpiredAccounts() {
        System.out.println("Yes, I am a scheduled job.");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM