【问题标题】:Cron to run at 12:00 AM every day using Spring Scheduler使用 Spring Scheduler 在每天凌晨 12:00 运行 Cron
【发布时间】:2015-12-29 09:56:48
【问题描述】:

我每天都在尝试执行一个方法,我已经使用 Spring 添加了调度程序但它没有被执行。

<task:scheduled-tasks scheduler="myScheduler">
    <task:scheduled ref="logDeletionTask" method="deleteExpiredLogs" cron="0 0 0 * * ?" />
</task:scheduled-tasks>
<task:scheduler pool-size="25" id="myScheduler"/>

【问题讨论】:

  • 也许你在不同时区的机器或服务器上运行代码

标签: spring cron cronexpression spring-scheduled


【解决方案1】:

对我来说,您正在寻找的 cron 表达式是:0 0 12 * * ?

这是一个适合您的工作示例:

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

    <bean id="logDeletionTask" class="task.Task" />

    <task:scheduled-tasks scheduler="myScheduler">
        <task:scheduled ref="logDeletionTask" method="deleteExpiredLogs" cron="0 0 12 * * ?" />
    </task:scheduled-tasks>

    <task:scheduler pool-size="25" id="myScheduler"/>
</beans>

任务豆:

package task;

import java.util.Date;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Task {

    public static void main(String[] args) throws InterruptedException {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        while (true) {
            Thread.sleep(1000);
        }
    }

    public void deleteExpiredLogs() {
        System.out.println(new Date());
    }
}

【讨论】:

  • 我认为这个表达式会安排在中午 12 点工作。
  • 表达式的第三部分是小时,应该是从 0 到 23(0 表示 12 PM)。如果您希望在中午 12 点触发作业,则正确的表达式为 0 0 0 * * ? 如果您希望在上午 12 点触发,则为 0 0 12 * * ?
  • 如果 0 对应于下午 12 点,因此 1 对应于下午 1 点,而 13 对应于凌晨 1 点,那么您的答案就有问题,任何人都无法接受
猜你喜欢
  • 2011-11-11
  • 2013-01-20
  • 2021-07-12
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多