Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite loop + Thread.sleep replace cron job

So I've had an idea in my head today... And I would like to hear some feed-back. I have a Java app which needs to check a directory every 5 minutes. Plain and simple the app needs to run every five minutes.

Seems like a good candidate for cronjob, but I was wondering... why not keep the logic/timing all within the app like so (simplified obviously):

public static void main(String[] args) {
    while(true) { // repeatedly execute...
        // do the work/job
        Thread.sleep(600 * 1000); // make the thread sleep for 5 minutes
    }
}

One significant downside I see is "How do we stop this app once it starts? Deleting it?

Are there any other significant draw-backs to this besides that one?

Should I stop daydreaming and just use cron jobs?

like image 241
Don Cheadle Avatar asked May 23 '26 10:05

Don Cheadle


1 Answers

A number of significant drawbacks:

  • If you ever want to change the polling frequency (i.e. do it every 2 minutes, or every 10 minutes), you have to change the program. This is especially difficult if you have an irregular polling schedule, something like once every 5 minutes on Monday through Friday, but once every 15 minutes on Saturday and Sunday. Sure, you don't think your program will ever need to do that, but requirements evolve.
  • As you say, killing the process is the only way to stop the program. And killing it in mid-process might be a bad thing. You could of course add some cancel logic, but that's additional development time.
  • The program is occupying memory while it's sitting there doing nothing (most of the time). This is a waste of resources. Probably not a huge deal when you're working with a system that has many gigabytes of memory, but it becomes an issue when you're working on embedded systems with limited memory.
  • You're wasting your time writing your own scheduling, which you then have to debug and maintain, when there's already a perfectly good scheduler built into the operating system.

I call this program a "catnap program" because it acts just like a cat: it sleeps most of the time, waking up now and then to stretch and maybe bat a string around for a few minutes, and then goes back to sleep. Programs are not cats.

like image 145
Jim Mischel Avatar answered May 24 '26 22:05

Jim Mischel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!