How to set up cron to run once a day at random times

ぐ巨炮叔叔 提交于 2021-01-27 07:12:38

问题


Hi so right now I have a basic cron that runs my stuff twice a day at 1 and 6. Something like:

H 1,18 * * *

The problem is I have like 100 things kicking off at this time which is clogging up my machine. I want to randomly generate a time once a day for each job to run. It's ok if 5-7 are going at once. So I guess my question is. For one is this possible? If so is there a best practice for this? I'm loading everything up in groovy so I was just thinking about generating a number between 1-24 and adding it to this:

cron('H 1,18 * * *')

if that's possible. But I feel like that would still clog me up since I have so many things kicking off.


回答1:


I went with this:

H H(0-7) * * *

which seems to be giving it a random time between 12 and 7 which is good for me. You could also do something like:

    def rand = Math.abs(new Random().nextInt() % 24) + 1;
    triggers {
        githubPush()
        cron('H ' + rand + ' * * *')
    }

but seems extra as what I did worked.




回答2:


Well, there is no syntax to do exactly that that I am aware of (athough you could make up some cludges in bash that would automatically regenerate crontabs every night say). But really why?? You don;t need to generate random times each day according to your description. You need to randomise it once and write those random times once into your crontab.

So, roll some dice, or use some basic rnd number generator. Or, better yet, distribute them uniformly - say each hour you kick off a handful of processes in your contab. Why would you need anything more elaborate? This is how its done anyways..




回答3:


I don't know if you can actually do this with cron, but if you have access to systemd Timers and services (and they're usually available in modern Linuxes from at least a few years back), you may be able to jury-rig a timer-based system.

Throw a small shell script that randomly sleeps and returns zero, or even just use the timers to delay the stuff in start-up.




回答4:


From jenkins docs:

In addition, @yearly, @annually, @monthly, @weekly, @daily, @midnight, and @hourly are supported as convenient aliases. These use the hash system for automatic balancing. For example, @hourly is the same as H * * * * and could mean at any time during the hour. @midnight actually means some time between 12:00 AM and 2:59 AM.

So you can use @daily



来源:https://stackoverflow.com/questions/47778209/how-to-set-up-cron-to-run-once-a-day-at-random-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!