【问题标题】:Schedule Spring job so it should not run on 2nd and 4th saturday安排 Spring 作业,使其不应该在第 2 和第 4 个星期六运行
【发布时间】:2016-09-15 06:44:24
【问题描述】:

我想在工作日和星期六运行我的春季计划工作。(星期六不应该是每月的 2 号和 4 号)。有没有办法使用spring表达式来实现这一点。

public class PayoutJob {

@Scheduled(cron="0 0 11 1 * MON-FRI")
public void payout(){
    System.out.println("Started cron job");

    // some business logic
   }
}

上述作业在工作日上午 11 点运行 IST。有没有办法计算第二个和第四个星期六的逻辑并将其放入 spring 表达式中以避免在那些日子运行作业。

【问题讨论】:

    标签: spring spring-scheduled


    【解决方案1】:

    我的建议是,保持简短:

    public class PayoutJob {
    
        @Scheduled(cron="0 0 11 1 * MON-FRI")
        public void payoutMonFri(){
            doJob();
        }
    
        @Scheduled(cron="0 0 11 1 * SAT")
        public void payoutSat(){
            if(!is2ndOr4thSaturday()){
                doJob();
            }
        }
    
        void doJob(){
            System.out.println("Started cron job");
            // some business logic
        }
    
        boolean is2ndOr4thSaturday(){
    
            Calendar c = Calendar.getInstance();
    
            int dayOfWeek  = c.get(Calendar.DAY_OF_WEEK);
            if(dayOfWeek == Calendar.SATURDAY){
                int today = c.get(Calendar.DAY_OF_MONTH);
                c.set(Calendar.DAY_OF_MONTH, 1); // reset
                int saturdayNr = 0;
    
                while(c.get(Calendar.DAY_OF_MONTH) <= today){
                    if(c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
                        ++saturdayNr;
                    }
                    c.add(Calendar.DAY_OF_MONTH, 1);
                }
    
                return saturdayNr == 2 || saturdayNr == 4;
            }
    
            return false;       
        }
    }
    

    我已按照我的要求更正了 while 循环条件。

    【讨论】:

    • 感谢您的快速解决方案。看起来不错..您能否建议 !is2dn() && !is4th() 方法实现。到目前为止我还没有使用过 java 8..所以不熟悉新的 java 日期时间 API。
    • 很好的答案.. 工作.. 非常感谢@dit。
    • 哦,当然。小错误:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-10
    • 1970-01-01
    相关资源
    最近更新 更多