LoginSignup
3

More than 3 years have passed since last update.

Node.jsのコードを定期実行する(crontabを利用)

Posted at

これまでのおさらい

今回のお話

  • node.jsをcrontabで定期実行する。

前回書いたコードは、「BME280センサーの値を読み取り、Google スプレッドシートに書き込む」というものでした。
これは一回だけ実行する作りになっています。
このままでは、毎回手動で実行する必要があります。

// デバイスに接続
const Obniz = require("obniz"); // デバイスに接続
var obniz = new Obniz("****-****"); //Obnizの番号を指定
var webclient = require("request");


obniz.onconnect = async function () {
  const ifttt_event = "Record"; //イベント名
  const ifttt_secret_key = "あなたのキーを書く"; //キー
  const IFTTT_URL_GoogleSheets = 'https://maker.ifttt.com/trigger/' + ifttt_event + '/with/key/' + ifttt_secret_key;

  const bme280 = obniz.wired("BME280", {vio:0, vcore:1, gnd:2, csb:3, sdi: 4, sck: 5, sdo:6 });
  await bme280.applyCalibration();
  await bme280.setIIRStrength(1);

  val = await bme280.getAllWait();


  //obniz画面表示
  obniz.display.clear();
  obniz.display.print("temperature:" + val.temperature.toFixed(1)) //気温
  obniz.display.print("humidity:" + val.humidity.toFixed(1)) //湿度
  obniz.display.print("pressure:" + val.pressure.toFixed(1)) //気圧



  //送信データ作成
  const p1 = val.temperature.toFixed(1);
  const p2 = val.humidity.toFixed(1);
  const p3 = val.pressure.toFixed(1);

  //IFTTTリクエスト
  webclient.post({
    url: IFTTT_URL_GoogleSheets,
    headers: {
    "content-type": "application/json"
    },
    body: JSON.stringify({'value1': p1, 'value2':p2, 'value3':p3})
    }, function (error, response, body){
    console.log(body);
  });

  obniz.close();//Obniz切断
}

Node.jsのコードを定期実行する方法

今回は、crontabで試してみます。

crontabの設定

crontabでは、コマンドのフルパスが必要です。

whichコマンドで、nodeコマンドのフルパスを調べます。
/home/pi/.nodebrew/current/bin/node の部分を使います。
~/myapp/BME280.js の部分が実行するファイルです。

pi@raspberrypi:~/myapp $ which node
/home/pi/.nodebrew/current/bin/node

crontabは、-eオプションが編集です。

pi@raspberrypi:~/myapp $ crontab -e

先程調べたnodeのフルパスを指定し、実行するファイルを指定します。
以下の設定を登録しました。
*/10 の部分が、10分周期で実行の意味となります。
参考:crontabの書き方

*/10 * * * * /home/pi/.nodebrew/current/bin/node ~/myapp/BME280.js

-lオプションがリスト表示です。

pi@raspberrypi:~/myapp $ crontab -l

(略)

*/10 * * * * /home/pi/.nodebrew/current/bin/node ~/myapp/BME280.js

実行結果

Google スプレッドシートのデータを見てみます。

crontabで実行されたコードによって、10分周期に気温、湿度、気圧が記録されています。

10minits.PNG

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
3