Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call flock with node.js?

Tags:

node.js

flock

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

like image 250
Eric Fong Avatar asked Apr 12 '11 09:04

Eric Fong


1 Answers

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

like image 95
Evan P. Avatar answered Oct 17 '22 07:10

Evan P.