iT邦幫忙

5

【學習筆記】 .NET 5/Core Console 在 Linux 平台排程運行

這次嘗試用 .NET5 在 Linux 做 Console 排程器並定期發送每日剩餘零花錢訊息到我跟家人的手機,突破點在之前都是架設在 windows server 並使用 windows task scheduler 或是 Quartz.NET 定期運行 .net console exe。


影片:

Yes


步驟:

第一步 : 個人推薦使用 GCP 的微型方案 ubuntu VM (1vCPU + 0.6GB 記憶體的方案) 架設Linux Server,原因在免費又有完整的VM環境,足夠我們拿來跑一些簡單小排程器。

第二步 : 寫好我們的 .net5/core console,假如邏輯簡單又不計較時間誤差、不想添加其他依賴,可以使用 while + threadsleep 排程作法,如:

using System;
using System.Threading;

namespace ScheduleRunOnLinuxConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            while(true)
            {
                Console.WriteLine("Sent Message");
                Thread.Sleep(TimeSpan.FromSeconds(5));
            }
        }
    }
}

除此外建議使用像是 Quartz.NET 套件安排排程時間。

第三步 : dotnet cli build 打包

dotnet publish -c Release -r linux-x64

.NET 5 預設 self-contained 為 true,優點是可以方便直接運行,但大小多增加幾十MB

image-20210218174030265

假如GCP上面有安裝 .NET SDK/Runtime 環境可以加上--self-contained false,減少檔案大小

dotnet publish -c Release -r linux-x64 --self-contained false

image-20210218174532208

第四步 : 接著打包成 zip文件藉由 GCP cloud shell 上傳到 VM

image-20210218181320182

image-20210218175024141

並使用 unzip 指令解壓縮image-20210218175438453

第五步 : 使用 chmod -R 755 路徑 添加運行權限,否則會出現圖片 Permission denied 錯誤

image-20210218175658278

添加權限後測試運行結果

image-20210218175854925

第六步 : 接著會發現假如 shell 關閉,運行的 console 也會跟著中斷,所以要使用 unsup..& 放到後台運行,另外使用 > 路徑 2>&1 保存log紀錄。

$nohup dll路徑 > 保存log路徑.log 2>&1 &

image-20210218180234190

Ubuntu Cron 排程器做法

類似 windows scheduler,可以借助本身系統來安排排程,好處是每次運行完 console 就釋放資源,語法使用靈活的 cron。

舉例 :
將上面範例代碼刪除 while

using System;
using System.Threading;

namespace ScheduleRunOnLinuxConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Sent Message");
        }
    }
}

並藉由 crontab 每分鐘跑一次 console 指令如下:

$ crontab -e
*/1 * * * * 運行路徑 

image-20210218182415631


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言