[英]How should I start a node.js script automatically
I want to start my script like every 30-60 minutes and don't want that the script is running all the time.我想每 30-60 分钟启动一次我的脚本,并且不希望脚本一直运行。
Can I do some sort of cronjob or something else, that is starting the script and closes it after it's done?我可以做某种cronjob或其他什么,即启动脚本并在完成后关闭它吗?
I'm using Ubuntu 18.04我正在使用 Ubuntu 18.04
Although cron works, a modern, reliable way to do this on Linux platforms is to create a systemd
service.尽管 cron 有效,但在 Linux 平台上执行此操作的一种现代、可靠的方法是创建
systemd
服务。 By creating a service, systemd
will automatically create a process and restart it if it exits or fails.通过创建服务,
systemd
会自动创建一个进程并在它退出或失败时重新启动它。 To create a systemd
service, do the following.要创建
systemd
服务,请执行以下操作。
Create a file in /etc/systemd/system
with the .service
extension.在
/etc/systemd/system
创建一个扩展名为.service
。 This file specifies the process we want systemd to keep an eye on.该文件指定了我们希望 systemd 关注的进程。
In the file, we can choose what command starts the script, how long to wait before retrying if the processes exits, what user is creating the process, etc. This article and this article both list some common parameters.在文件中,我们可以选择启动脚本的命令、进程退出重试前等待多长时间、创建进程的用户等。本文和本文都列出了一些常用参数。 In your case, you want your file to look something like...
在您的情况下,您希望您的文件看起来像......
[Unit]
Description=Runs script every 30 minutes
After=network-online.target
Requires=network-online.target # if your script connects to the internet, for example
Documentation= # maybe your github or something
[Service]
Type=simple
Restart=always
RestartSec=1800 # 30 minutes
User= # Your user, if you need particular permissions for example
WorkingDirectory= # The working directory you need
ExecStart= # The command to start the script you need
systemctl enable your_service_name.service
.systemctl enable your_service_name.service
启动您的服务。 This will make sure your service runs each time the system is booted (replace enable
with disable
to stop the service from starting on boot).enable
替换为disable
以阻止服务在启动时启动)。 If you need it to run during THIS boot, use systemctl start your_service_name.service
(switching start
with stop
does what you expect).systemctl start your_service_name.service
(切换start
和stop
符合您的预期)。 This is elaborated on in the articles above.Create a script file like run_script.sh and put the following code in.创建一个脚本文件,如 run_script.sh 并放入以下代码。
exec node /path/to/your/javascript.js
Then add this run_script.sh to your cronjob.然后将此 run_script.sh 添加到您的 cronjob。 You can use
*/30 * * * *
to run it every 30 min or 0 * * * *
to run it hourly.您可以使用
*/30 * * * *
每 30 分钟运行一次,或使用0 * * * *
每小时运行一次。
If your script does not stop by itself, you can add a process.exit()
after a condition to do it.如果您的脚本不会自行停止,您可以在条件后添加
process.exit()
来执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.