Untitled
unknown
plain_text
2 years ago
1.8 kB
1
Indexable
Never
以下範例,是先建立一個 loop script,在 Amazon Linux 中,使用 systemctl 命令來運行的簡單範例. 1) 首先創建一個 loop 迴圈的 script 腳本,只是每秒打印時間到特定檔案中。 $ cat /home/ec2-user/sample.sh #!/bin/sh while true do date >> /tmp/log.txt sleep 1 done $ chmod 755 /home/ec2-user/sample.sh $ /home/ec2-user/sample.sh ^C $ tail -3 /tmp/log.txt 日 5月 22 02:36:26 UTC 2022 日 5月 22 02:36:27 UTC 2022 日 5月 22 02:36:28 UTC 2022 2) 接下來在目錄 /lib/systemd/system/ 下創建一個配置檔,可以參考該目錄下的其他服務配置,來調整你的配置。 記得要重啟載入 $ sudo systemctl daemon-reload。 $ cat /lib/systemd/system/sample.service [Unit] Description=sample After=network.target [Service] Restart=always WorkingDirectory=/usr/bin/ ExecStart=/home/ec2-user/sample.sh [Install] WantedBy=multi-user.target $ sudo systemctl daemon-reload 3) 最後測試一下是否有正常運行。 $ sudo systemctl status sample ● sample.service - sample Loaded: loaded (/usr/lib/systemd/system/sample.service; disabled; vendor preset: disabled) Active: inactive (dead) $ sudo systemctl start sample $ sudo systemctl status sample ● sample.service - sample Loaded: loaded (/usr/lib/systemd/system/sample.service; disabled; vendor preset: disabled) Active: active (running) since 日 2022–05–22 03:00:28 UTC; 4s ago Main PID: 11386 (sample.sh) CGroup: /system.slice/sample.service ├─11386 /bin/sh /home/ec2-user/sample.sh └─11396 sleep 1 5月 22 03:00:28 ip-10–0–200–161.us-west-2.compute.internal systemd[1]: Started sample. $ tail -f /tmp/log.txt Sun May 22 03:01:09 UTC 2022 Sun May 22 03:01:10 UTC 2022 Sun May 22 03:01:11 UTC 2022 Sun May 22 03:01:12 UTC 2022 ---