如何修改指定Cron表达式,实现周一至周五10点排除月末执行?
Absolutely! You can tweak your existing cron expression to meet this requirement—though the approach depends on which cron implementation you’re using (syntax varies across tools like Quartz, Spring Cron, or standard Linux cron). Let’s break this down clearly:
For Quartz Cron (your original syntax uses Quartz-specific elements like ? and the 7th year field)
Your original expression is:
0 0 10 ? * MON,TUE,WED,THU,FRI *
To exclude the last day of the month while keeping the Mon-Fri 10 AM schedule, adjust the day-of-month field (4th position) from ? to *!=L. Here’s the updated expression:
0 0 10 *!=L * MON-FRI *
What this does:
*!=Lin the day-of-month field means "all days except the last day of the month" (Lis Quartz’s shorthand for "last day").- We retain
MON-FRIin the day-of-week field to restrict execution to weekdays. - Quartz will only trigger the job when both conditions are satisfied: it’s a weekday and not the last day of the month, at exactly 10 AM.
For other cron implementations (like Linux/Spring Cron, which don’t support !=L)
If your cron tool doesn’t recognize the !=L syntax, you can’t fully express this logic in the cron expression alone. Instead, add a pre-check to the command you’re running:
- Keep the core schedule for Mon-Fri 10 AM:
0 0 10 * * 1-5 - Add a shell condition to skip execution on the last day of the month:
0 0 10 * * 1-5 if [ $(date +%d) -ne $(cal | awk 'NF {DAYS = $NF}; END {print DAYS}') ]; then /path/to/your/job; fi
This checks if the current day number doesn’t match the last day of the month (pulled from the cal command) before running your job.
内容的提问来源于stack exchange,提问作者akkapolk

