12

I have cron job to run node.js scripts.

Want to use flock to lock a file to make sure my cron jobs are not overlapped.

Any good module for doing file locking ?

Or I should call that in child process ?

Or I should not do any file locking ?

Sorry, I am new to this and not sure file locking is good for async env like node. Thanks

Eric Fong
  • 815
  • 1
  • 8
  • 17
  • I would just use a child-process because flock is so dead simple... as to whether file locking is good for async really depends on, as it does for most things, how you implement. Just be careful not to block I/O and you should be fine. – srquinn Sep 04 '12 at 18:33

2 Answers2

8

If you're just trying to keep cron jobs from overlapping, consider using the "flock" utility in your crontab instead.

If your cron line looks something like this:

*/10 * * * * /usr/bin/node /usr/local/share/myscript

You can just change it to this:

*/10 * * * * /usr/bin/flock -n /var/lock/myscript /usr/bin/node /usr/local/share/myscript

This will try to get the lock on the lockfile /var/lock/myscript. If it can, it will run the command on the rest of the line and then release the lock; if not (because there's another job running), it will fail.

This keeps you from having to add a lot of dependencies on 'fs-ext' and so on.

There's more information at http://linux.die.net/man/1/flock

Evan P.
  • 979
  • 1
  • 10
  • 17
  • Inspiration from http://mihasya.com/blog/a-quick-note-on-cron-utilities/ (Credit where credit is due) – Evan P. Nov 02 '12 at 17:37
  • I'm getting this error: `/bin/sh: -c: line 0: unexpected EOF while looking for matching `'' /bin/sh: -c: line 1: syntax error: unexpected end of file` – chovy Nov 24 '14 at 08:37
  • You can also avoid the fork() and unneeded subshell: https://blog.famzah.net/2013/07/31/using-flock-in-bash-without-invoking-a-subshell/ – famzah Jan 11 '21 at 08:08
4

See flock function in fs-ext package: https://github.com/baudehlo/node-fs-ext

alex
  • 11,935
  • 3
  • 30
  • 42