Dieses Blog durchsuchen

Mittwoch, 17. August 2016

node.js: install simple sheduler as a rebootsafe service on ubuntu 16.04

There are many situations, in whioch you want to process a serverside workerscript to process queued tasks. Here is a simple solution to setup a nodejs cron script wich runs as a systemd service on ubuntu.

In this sample we are logging a text every second to the console, the filesystem and to the system d status log.


Prerequisits

Installed node.js, npm


Create your project

create a folder "/var/www/html/sheduler"

Init a npm project

create a package.json with following content

open a terminal and run
$ npm install

Install the sheduler

We want to use node-cron for our sheduler.  Node-cron allows us to trigger a script every second. That is ideal, if you want to build a worker wich runs every second. install follwing script 


This simple script creates a logger to log to the filesystem and to console every second. The logfile path is set to /var/www/html/sheduler/all-log.log


Install sheduler as a systemd service


To make our sheduler reboot save we now add the script as a systemd service.

add a file:
/etc/systemd/system/nodecron.service

paste following script in this service unit

This adds a servicedesfinition with the information, what script to execute.

Test your systemd-service

At last we reload our service units by typing:
$ systemctl --system daemon-reload

Enable your service
$ systemctl enable nodecron

 Start your service
$ systemctl start nodecron


Get status
$ systemctl status nodecron 

 If everything works you will get a status like that:

This tells us, that our logger logs every second a info and a debugmessage.
As you can see, our node.js script gets executed successfully. The service is tunning even, if you reboot the machine.

At the end you will find a logfile with your 2 loggings under:
/var/www/html/sheduler/all-logs.log

Disable your service like that
$ systemctl disable nodecron



Keine Kommentare:

Kommentar veröffentlichen