สำหรับใครที่เขียนโปรแกรมด้วยภาษา Python แล้วเจอปัญหาการรันโปรแกรมไว้บน Web Server หรือในเครื่องคอมพิวเตอร์ของเราเอง เมื่อเครื่อง reboot หรือเราทำการ reboot ด้วยตัวเองแล้วโปรแกรมที่เรารันทิ้งไว้เกิดดับหรือไม่ทำงาน ผมก็มีวิธีแก้ไขปัญหานั้นมาบอก อันดับแรกให้เราสร้างไฟล์ service โดยการเปิด terminal
เปิด terminal ขึ้นมาแล้วใช้คำสั่งนี้
sudo nano /lib/systemd/system/htmltopdf.service
ตามตัวอย่างนี้
จะได้ผลดังนี้
เมื่อได้ผลตามรูปแล้วจากให้ทำการพิมพ์คำสั่งลงในไฟล์ service ที่สร้างขึ้นมา
[Unit]
Description=MDsoft HTMLToPDF Service
After=multi-user.target
[Service]
Type=simple
WorkingDirectory=[ใส่ path directory ก่อนตำแหน่งของโฟรเดอร์โปรแกรม ]/htmltoPdfImage2
ExecStart=/usr/bin/python [ใส่ path directory ก่อนตำแหน่งของโฟรเดอร์โปรแกรม ]/htmltoPdfImage2/index.py
[Install]
WantedBy=multi-user.target
ตัวอย่างตามนี้
[Unit]
Description=HTMLToPDF Service
After=multi-user.target
[Service]
Type=simple
WorkingDirectory=/home/robot/htmltoPdfImage2
ExecStart=/usr/bin/python /home/robot/htmltoPdfImage2/index.py
[Install]
WantedBy=multi-user.target
เมื่อพิมพ์เสร็จให้กด ctrl - x จากนั้นพิมพ์ Y เพื่อทำการ save
จากนั้นทำการรีโหลดไฟล์ service ด้วยคำสั่งนี้
sudo systemctl daemon-reload
จากนั้นทำการ enable ไฟล์ service ด้วยคำสั่งนี้
sudo systemctl enable htmltopdf.service
ผลที่ได้ตามด้านล่างนี้
จากนั้นทำการ start service โดยใช้คำสั่งนี้
sudo systemctl start htmltopdf.service
สามารถตรวจสอบว่าไฟล์ service นั้น ทำงานหรือไม่ โดยใช้คำสั่งนี้
sudo systemctl status htmltopdf.service
จะได้ผลตามรูปด้านล่างนี้
จากนั้นให้ทำการตรวจสอบว่าโปรแกรมทำงานหรือไม่
ในการสร้างไฟล์ service บน ubuntu เพื่อใช้รันโปรแกรมตอนเราเปิดเครื่องหรือตอนที่เครื่องทำการ reboot นั้นสามารถนำใช้ไปได้อีกหลากหลายโปรแกรม สามารถนำวิธีอันนี้ไปต่อยอดเพิ่มได้นะครับ
อ้างอิง
tecadmin(2562).[ออนไลน์].How To Setup Autorun a Python Script Using Systemd.เข้าถึงได้จาก https://tecadmin.net/setup-autorun-python-script-using-systemd/
Dexter Industries(2563).[ออนไลน์].Run a Program On Your Raspberry Pi At Startup.เข้าถึงได้จาก https://www.dexterindustries.com/howto/run-a-program-on-your-raspberry-pi-at-startup/
stackoverflow(2563).[ออนไลน์].เข้าถึงได้จาก https://stackoverflow.com/questions/51025312/start-a-python-script-at-startup-automatically