简体   繁体   中英

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. 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. 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. The next week I want to run the exact same program except I want to run it for the 15th. 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? 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. 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.

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:

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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