I am programming a website on a Linux CentOS server (I am planning to upgrade to a VPS plan where I will have root access). Much of the website will rely on scripts that are automated.
I have 2 questions about starting automated processes.
-
Is there any way I can start a Daemon thread, or anything like that, which will constantly be running. I need to execute a script every time an email account gets a new e-mail. I am aware of cron jobs that can run every minute, but having a script that constantly runs would be ideal, so I can execute the script the moment a new e-mail arrives.
-
Is there any way from code (ideally PHP) to start a thread, which runs concurrently with the main program. In the script I am using, the imap_open is used to connect to an e-mail account, which takes a few seconds every time. However, if I could fire off multiple concurrent scripts at the same time, that would ideally reduce the program’s time. Is there any way to do this?
Any help with these questions would be greatly appreciated.
For the first part, there’s two easy solutions:
Use the Vixie cron
@rebootstart specification to start your daemon at reboot as a standard user. This and every-minute cron-jobs are the only mechanisms that make it easy to run a daemon-style service as a user.Use
procmailto start a new script on every email delivery. The downside here is thatprocmailwill run and then start a new program on every email — when you’re getting a hundred emails per second, this could be a serious hindrance compared to a daemon that usesinotify(7)to alert a long-lived program about new emails.For the second part, look for a wrapper for the
fork(2)system call. It cleaves a program cleanly in half — parent and child — and allows each to continue independent execution from then on. If the child and parent need to communicate again in the future, then perhaps see if PHP supports threaded execution.