jasonlvhit / gocron

A Golang Job Scheduling Package.
BSD 2-Clause "Simplified" License
3.45k stars 346 forks source link

Hey, how do I set the last day of the month to be executed on time? #106

Open JokerDevops opened 5 years ago

JokerDevops commented 5 years ago

Hey, how do I set the last day of the month to be executed on time?

PriyaSharma45 commented 5 years ago

Did you find any way to do it?

JohnRoesler commented 4 years ago

It doesn't look like there is a way to do that currently. Seems like a feature would need to be added. Perhaps a Monthly() option that allows for things like FirstDay(), LastDay(), DayOfMonth(15).

JokerDevops commented 4 years ago

Yes, currently he needs FirstDay(), LastDay(), DayOfMonth(15)

wishdev commented 4 years ago

I'm not certain this is the purview of gocron.

For example, I've needed to create a report on the 12th of each month - EXCEPT if the 12th was on the weekend and then it was either the 11th if the 12th was a Saturday or the 13th if the 12th was a Sunday. That would be an interesting set of options to describe in a single line of gocron scheduling.

So, maybe something like this for the question at hand

 func coreTask() {
     fmt.Println("Must be last day of month - time to make the donuts")
 }

 func task() {
     now := time.Now()
     currentYear, currentMonth, currentDay := now.Date()
     currentLocation := now.Location()

     firstOfMonth := time.Date(currentYear, currentMonth, 1, 0, 0, 0, 0, currentLocation)
     lastOfMonth := firstOfMonth.AddDate(0, 1, -1)
     if lastOfMonth.Day() == currentDay {
         coreTask()
     }
}

gocron.Every(1).Day().At("10:30").Do(task)

Last day of month code from here

JohnRoesler commented 4 years ago

I like your solution @wishdev! Seems very reasonable to handle outside of gocron as to your point - the options could be highly involved getting exactly the right cron schedule unless it was a simple, I want this date of the month always, or the first day or last day.

003random commented 3 years ago

Nice solution @wishdev. Was also looking for something similar and this does the job. Good enough for me 👍

JohnRoesler commented 3 years ago

@003random come check out our active fork https://github.com/go-co-op/gocron we’ve added support for Monthly schedules 👍

003random commented 3 years ago

Oh awesome! Thanks @JohnRoesler