Last active
October 3, 2018 00:17
-
-
Save noriyukitakei/0d609e41c2875c265c1aff1612959a91 to your computer and use it in GitHub Desktop.
クラウドデザインパターンを実践してみたシリーズ 〜 Scheduler Agent Supervisorパターン〜【retryTask】
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MySQLのモジュールを読み込む | |
const mysql = require('mysql2'); | |
// ファイルを読み込むためのモジュールを読み込む | |
const fs = require('fs'); | |
module.exports = function (context, myTimer) { | |
var timeStamp = new Date().toISOString(); | |
if(myTimer.isPastDue) | |
{ | |
context.log('JavaScript is running late!'); | |
} | |
// MySQLに接続するための情報を環境変数から取得する。 | |
context.log('JavaScript timer trigger function ran!:', timeStamp); | |
var conn = mysql.createConnection( | |
{host: process.env['MYSQL_HOST'], | |
user: process.env['MYSQL_USER'], | |
password: process.env['MYSQL_SECRET'], | |
database: process.env['MYSQL_DB'], | |
port: 3306, | |
ssl:{ca:fs.readFileSync(process.env['MYSQL_CA'])} | |
} | |
); | |
conn.query( | |
// 失敗回数が3回以下で、process_stateが03(失敗)もしくはcomplete_byが現在時刻より大きい(つまり完了予定時間を過ぎている) | |
// タスクを抽出する。 | |
'SELECT * FROM `t_state_store` where failure_count < 4 and (process_state = "03" or complete_by > NOW())', | |
function (error, results, fields) { | |
var messages = []; | |
try { | |
for (var i = 0;i < results.length;i++) { | |
// process_stateが03(失敗)のタスクを以下のように更新します。すると、以下のレコードをSchedulerが抽出して、 | |
// もう一度Agentに処理を依頼します。つまりリトライです。 | |
// locked_by:NULL | |
// complete_by:NULL | |
// process_state:00 | |
// failure_count:1をインクリメント | |
conn.query( | |
'UPDATE `t_state_store` SET locked_by = NULL,complete_by = NULL,process_state = "00",failure_count = failure_count + 1' | |
+ ' where task_id = ' + results[i].task_id, | |
function (error, results, fields) { | |
if(error) throw error; | |
} | |
) | |
} | |
} catch (e) { | |
context.log(e); | |
throw e; | |
} finally { | |
context.log("close"); | |
conn.end(); | |
} | |
context.done(); | |
} | |
) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment