基于注解的Spring调度器,即’@Scheduled’,并不按照cron表达式持续运行。

huangapple go评论86阅读模式
英文:

Spring Annotation based scheduler i.e '@Scheduled' is not running continuously as per cron expression

问题

我已经使用基于注解的 Spring 调度器 @Scheduler 并设置它每 30 秒运行一次。我的示范代码如下。

这是一个使用调度器注解的示范服务代码。

@Service
public class SchedulerJob
{
    @Scheduled(cron="*/30 * * * * ?")
    public void demoServiceMethod()
    {
        System.out.println("每隔 30 秒运行一次的任务");
    }
}

以上代码正常工作,每 30 秒运行一次,但有时候会停止运行。
当我重新启动服务器时,它又重新开始运行。

有谁能告诉我使用 @Scheduler 注解出现这种行为的原因。

提前感谢。

英文:

I have used Spring Annotation based scheduler @Scheduler and set it to run for every 30
seconds. My sample code is something like this.

This is a sample Service code to use Scheduler annotation.

 @Service
    public class SchedulerJob
    {
        @Scheduled(cron="*/30 * * * * ?")
        public void demoServiceMethod()
        {
            System.out.println("Job running every 30 seconds");
        }
    }

The above code is working fine and is running for every 30 seconds, but sometimes it is not
running.
When i restart the server, it is picking up again.

Can anyone tell me the reason for this kind of behaviour with the @Scheduler annotation.

Thanks in advance.

答案1

得分: -1

使用注解@EnableScheduling设置Spring配置。

@Configuration
@EnableScheduling
public class RootConfig { .. }

类似于cron的表达式,将传统的UNIX定义扩展到包括对秒、分钟、小时、月份和星期的触发器。例如:"0 * * * * MON-FRI"表示在工作日每分钟触发一次。

cron具有60秒的精度,不是最佳工具。如果您经常运行它,cron不会到达子分钟分辨率,您将需要找到另一种方法。

尝试使用表达式initialDelayString定义在第一次执行之前延迟的毫秒数,以及fixedDelayString以毫秒为单位在上一次调用结束和下一次调用开始之间执行带有固定周期的注释方法。

@Scheduled(initialDelayString = "${initialDelayString}", fixedDelayString = "${fixedDelayString}")
public void demoServiceMethod()
英文:

Set Spring configuration with the annotation @EnableScheduling

@Configuration
@EnableScheduling
public class RootConfig { .. }

A cron-like expression, extend the usual UNIX definition to include triggers on the second as well as minute, hour, day of month, month and day of week. e.g. "0 * * * * MON-FRI" means once per minute onweekdays.

cron has a 60 seconds of granularity, itsn't the best tool to use. If you run it that often, cron does not go down to sub-minute resolutions, you will need to find another way.

Try to use the expression initialDelayString defines the milliseconds to delay before the first execution and fixedDelayString execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.

@Scheduled(initialDelayString = "${initialDelayString}", fixedDelayString = "${fixedDelayString}")
public void demoServiceMethod()

huangapple
  • 本文由 发表于 2020年4月4日 02:38:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/61018397.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定