I am attempting to deploy a listener to a VPS, which will run 24/7.
The boilerplate for the listener is below:
from concurrent.futures import TimeoutError
from google.cloud import pubsub_v1
# TODO(developer)
# project_id = "your-project-id"
# subscription_id = "your-subscription-id"
# Number of seconds the subscriber should listen for messages
# timeout = 5.0
subscriber = pubsub_v1.SubscriberClient()
# The `subscription_path` method creates a fully qualified identifier
# in the form `projects/{project_id}/subscriptions/{subscription_id}`
subscription_path = subscriber.subscription_path(project_id, subscription_id)
def callback(message: pubsub_v1.subscriber.message.Message) -> None:
print(f"Received {message}.")
message.ack()
streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback)
print(f"Listening for messages on {subscription_path}..\n")
# Wrap subscriber in a 'with' block to automatically call close() when done.
with subscriber:
try:
# When `timeout` is not set, result() will block indefinitely,
# unless an exception is encountered first.
streaming_pull_future.result(timeout=timeout)
except TimeoutError:
streaming_pull_future.cancel() # Trigger the shutdown.
streaming_pull_future.result() # Block until the shutdown is complete.
My question is, if I deploy this to a VPS and run python3 listener.py
will this continue to run even when I close my connection to the VPS? If not, how do I deploy and run this program so that it continues listening 24/7?
No, the program will close when the SSH connection is complete.
There are two main ways to avoid this: Docker and manual deployment. I'll show you an example of the second way. You can read about Docker yourself.
Make a file listener.service
next to your script:
[Unit]
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/bin/python3 /usr/local/bin/listener-247
Restart=always
[Install]
WantedBy=multi-user.target
And another Bash script deploy.sh
. You have to run it to update the version of your software on the server. Replace the value of the variable SERVER_SSH
with your own. This script assumes that you are logged on to the server as root:
#!/usr/bin/bash
[email protected]
scp ./listener.py $SERVER_SSH:/usr/local/bin/listener-247
ssh $SSH_SERVER chmod 755 /usr/local/bin/listener-247
scp ./listener.service $SERVER_SSH:/lib/systemd/system/listener-247.service
ssh $SSH_SERVER systemctl daemon-reload
ssh $SSH_SERVER systemctl enable listener-247
ssh $SSH_SERVER systemctl restart listener-247