pwshub.com

How to Restart Service When Text Not Found on Webpage

Restarting the service automatically when specific text doesn’t exist on a webpage is a good trick to keep the application functional while you fix the real issue.

While working on Geekflare Tools, we noticed that front-end is losing connection with CMS for some reason; hence webpage shows default content which gives bad user experience and confuses search engines.

I am using headless CMS called Directus to manage content.

geekflare website audit page broken

Finding the real root cause is time-consuming and while waiting for real issue fixes, here is the workaround I followed and you can do too.

  • Requirement – auto-restart services when expected content doesn’t exist on a webpage.
  • What to restart – CMS and front-end service. (technically, you can restart anything depending on your needs)

I used Python with BeautifulSoup module to do the following.

  • Scrape webpage (ex – https://geekflare.com/tools/website-audit)
  • Look for expected content (ex – Geekflare Website Audit)
  • If expected content not found then restart CMS and front-end service
  • Put script in crontab to run every 10 minutes

It is advisable to do this on the server where the services run, so you avoid the complexity of running scripts remotely.

  • Login to server (I am using Ubuntu)
  • Create a .py file (autostart.py) in your desired folder and use below script
import requests
from bs4 import BeautifulSoup
import os
import time
# URL to scrape, feel free to change this per your needs.
url = "https://geekflare.com/tools/website-audit"
# Send a request to fetch the webpage content
response = requests.get(url)
# Check if the request was successful
if response.status_code == 200:
    soup = BeautifulSoup(response.content, 'html.parser')
    # Check if the expected text is present on the page, change the text as you need.
    if "Geekflare Website Audit" not in soup.get_text():
        print("Expected Text not found, running custom script...")
        # Directus CMS Docker container
        os.system('/usr/bin/docker restart directus')
        # Giving sleep for 30 seconds to allow the restart process to complete
        time.sleep(30)
        # Restart frontend using PM2
        os.system('/usr/bin/pm2 restart tools_fe')
        print("Autostart script executed successfully.")
    else:
        print("Expected Text found, no action needed.")
else:
    print(f"Failed to fetch the page. Status code: {response.status_code}")

I’ve added the comment inside the script so you can adjust the necessary details per your needs.

  • Save the file, let’s call it autostart.py
  • Add the Python script in crontab
  • Open crontab
crontab -e
  • Add below and save the crontab
*/10 * * * * /usr/bin/python3 /path/to/autostart.py >> /path/to/autostart.log 2>&1

Above tiny script will run through system cron every 10 minutes to scrape a webpage and restart services when expected content doesn’t exist on a webpage. I would advise testing the script to ensure it works for you.

  • Chandan Kumar

    Chandan Kumar is a founder of Geekflare. He is a technology enthusiast and entrepreneur who is passionate about helping businesses and individuals around the world.

Was this helpful?

Thanks for your feedback.

Source: geekflare.com

Related stories
1 month ago - Nitro.js is a solution in the server-side JavaScript landscape that offers features like universal deployment, auto-imports, and file-based routing. The post Nitro.js: Revolutionizing server-side JavaScript appeared first on LogRocket Blog.
1 day ago - A 502 Bad Gateway error in Nginx may be a sign of more severe problems, so developers must know how to troubleshoot and resolve these errors.
1 month ago - Node-RED is a software development tool that provides a browser-based editor that makes it easy to automate flows for building IoT services. The post Enhance your workflow with Node-RED v4.0 appeared first on LogRocket Blog.
1 week ago - Docker hosting platform provides cloud infrastructure for users to deploy and manage Docker containers. This type of platform simplifies container scaling and offers an optimized environment for users to manage their containerized...
1 month ago - Forex VPS is a specialized hosting service that provides traders with a secure and stable environment to run Forex software. By using Forex VPS, traders can benefit from: Geekflare has researched and compiled the best Forex VPS hosting...
Other stories
6 minutes ago - Hina Kharbey talks about how the roles of a mentor versus a coach differ, as well as the situations that work best for having each one. The post Leader Spotlight: The difference between mentoring and coaching, with Hina Kharbey appeared...
3 hours ago - Fixes 41 bugs (addressing 595 👍). node:http2 server and gRPC server support, ca and cafile support in bun install, Bun.inspect.table, bun build --drop, iterable SQLite queries, iterator helpers, Promise.try, Buffer.copyBytesFrom, and...
7 hours ago - This guide provides a foundational understanding of Redux and why you should use it for state management in a React app. The post Understanding Redux: A tutorial with examples appeared first on LogRocket Blog.
9 hours ago - Discover some of the best Node.js web scraping libraries, including Axios and Superagent, and techniques for how to use them. The post The best Node.js web scrapers for your use case appeared first on LogRocket Blog.
12 hours ago - Infinite runner games have been a favorite for gamers and developers alike due to their fast-paced action and replayability. These games often feature engaging mechanics like endless levels, smooth character movement, and dynamic...