简体   繁体   English

安排 Java 作业每周运行一次,每次使用不同的参数

[英]Schedule a Java job to run once a week with different parameters each time

So I am currently designing an invoicing system that is meant to be run once a week.所以我目前正在设计一个每周运行一次的发票系统。 We separate our customers into 4 cycles that run once a week.我们将客户分成 4 个周期,每周运行一次。 What is the best way to schedule a Cron job to run once a week but to have a specific argument each time based on what day of the month it is.将 Cron 作业安排为每周运行一次但每次都根据月份中的哪一天进行特定参数的最佳方法是什么。 For example I want all customers that receive invoices on the 8th of the month to be sent out at 12:00AM on the 8th of each month.例如,我希望在每月 8 日收到发票的所有客户在每个月 8 日上午 12:00 发送。 The next week I want to run the exact same program except I want to run it for the 15th.下周我想运行完全相同的程序,但我想在 15 日运行它。 Should I have four separate jobs with 4 specific parameters that all run once a month or is there a sleeker way to keep everything in one program and one job that runs weekly but with different arguments?我应该有四个单独的作业,每个作业都有 4 个特定的参数,每个月都运行一次,还是有一种更时尚的方式将所有内容保存在一个程序和一个每周运行但具有不同参数的作业中? Am I overthinking it?是我想多了?

While dealing with sensitive business problems like the one you have described, I would never rely on cron scheduling to manage state.在处理您所描述的敏感业务问题时,我永远不会依赖cron调度来管理状态。 I would rather leave the state management entirely to the program.我宁愿将状态管理完全留给程序。

So, it is best to use a database or a file that stores the state so that scheduling has no influence on what your program does.因此,最好使用存储状态的数据库或文件,以便调度不会影响您的程序执行的操作。 With that approach, you can have a single cron job that is run once a week.使用这种方法,您可以拥有一个每周运行一次的cron作业。

The state information to be stored (based on what you have stated):要存储的状态信息(根据您的陈述):

  • customer顾客
  • cycle number循环数
  • last run date上次运行日期

The program must be capable of:该计划必须能够:

  • Not repeating (if it is run again within the same week, it should never repeat a cycle)不重复(如果在同一周内再次运行,则不应重复循环)
  • Fill the gap (if we run it after a gap of a week or more, it should be able to run all the missed cycles)填补空白(如果我们在一周或更长时间的间隔后运行它,它应该能够运行所有错过的周期)

You're overthinking it ;) You can have cron entry for all 4 cycles like this:你想多了 ;) 你可以像这样在所有 4 个周期都有 cron 条目:

0 0 8,15,22,29 * * command

and add case switch or if statements checking the day of month with date +"%d", but this would over complicate the task.并添加 case switch 或 if 语句用日期 +"%d" 检查月份中的某天,但这会使任务复杂化。 Not to mention readability.更不用说可读性了。

Other approach would be creating a wrapper script that would hold all the 'case' logic mentioned above and set the wrapper as a cron command.其他方法是创建一个包装器脚本,该脚本将保存上面提到的所有“案例”逻辑并将包装器设置为 cron 命令。 eg例如

day_of_month=$(date +'%d')
case "${day_of_month}" in
'8') params='your params here' ;;
...
esac
/your/program "${params}"

You can always keep it simple and use 4 separate crontab entries.您可以始终保持简单并使用 4 个单独的 crontab 条目。

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

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