How can you execute a Node.js script via a cron job?

后端 未结 7 1529
深忆病人
深忆病人 2020-12-02 08:58

Quite simply, I have node script that I want to execute once a month.

30 6 1 * * node /home/steve/example/script.js

But this doesn\'t work,

相关标签:
7条回答
  • 2020-12-02 09:07

    Additionally, just put #!/usr/local/bin/node at the top of the script you want to execute. Then it will automatically know to execute the script with node. Make sure the file is executable as well.

    0 讨论(0)
  • 2020-12-02 09:08

    I don't know if changing your relative paths in your script to absolute paths is a good idea
    (what happens when your file system changes or you deploy in another environment?)

    You could try wrapping it in a shell script, setting some environment variables in the crontab execution. (specifically PATH & NODE_PATH for starters)

    Try my suggestion for this similar question:
    https://stackoverflow.com/a/27823675/608269

    0 讨论(0)
  • 2020-12-02 09:17

    You can also specify paths to binary files on top of your user crontab like:

    PATH=/bin:/usr/bin:/usr/local/bin
    
    * * * * * cd your/path && node foo.js
    * * * * * cd your/path && npm run bar
    
    0 讨论(0)
  • 2020-12-02 09:18

    in my laptop using Linux mint the given path not working so i used this to get a work around.

    $ which node

    $ /usr/bin/node this worked for me.

    0 讨论(0)
  • 2020-12-02 09:22

    Use absolute paths for the node alias and the file to be run.

    Edit Cron Jobs

    crontab -e
    

    Entry to Run Our Node File

    This will run every minute.

    */1 * * * * * /bin/node /public/test.js
    

    Full Tutorial https://askmacgyver.com/blog/tutorial/how-to-run-node-scripts-from-a-cron-job

    0 讨论(0)
  • 2020-12-02 09:25

    just provide the full path to node /usr/local/bin/node in your cron job like:

    30 6 1 * * /usr/local/bin/node /home/steve/example/script.js
    
    0 讨论(0)
提交回复
热议问题