Spaces:
Sleeping
Sleeping
from flask import Flask, render_template_string | |
from apscheduler.schedulers.background import BackgroundScheduler | |
import subprocess | |
from datetime import datetime | |
app = Flask(__name__) | |
execution_logs = [] | |
MAX_LOG_ENTRIES = 20 | |
def run_cli_script(): | |
timestamp = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC") | |
log_entry = {'time': timestamp, 'output': '', 'error': ''} | |
try: | |
result = subprocess.run( | |
["python", "cli.py"], | |
capture_output=True, | |
text=True, | |
timeout=300 | |
) | |
log_entry['output'] = result.stdout | |
log_entry['error'] = result.stderr | |
except Exception as e: | |
log_entry['error'] = str(e) | |
finally: | |
execution_logs.append(log_entry) | |
if len(execution_logs) > MAX_LOG_ENTRIES: | |
execution_logs.pop(0) | |
# Initialize scheduler with a named job | |
scheduler = BackgroundScheduler(daemon=True) | |
scheduler.add_job( | |
run_cli_script, | |
'interval', | |
hours=3, | |
id='main_job', | |
next_run_time=datetime.now() # Initial run time | |
) | |
scheduler.start() | |
run_cli_script() # Initial run | |
def home(): | |
# Get the specific job by ID | |
job = scheduler.get_job('main_job') | |
next_run = job.next_run_time.strftime('%Y-%m-%d %H:%M:%S UTC') if job else 'N/A' | |
return render_template_string(''' | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Script Scheduler</title> | |
<meta http-equiv="refresh" content="10"> | |
<style> | |
body { font-family: Arial, sans-serif; padding: 20px; } | |
.log-box { | |
background: #000; | |
color: #0f0; | |
padding: 15px; | |
border-radius: 5px; | |
margin-top: 20px; | |
white-space: pre-wrap; | |
} | |
.timestamp { color: #888; margin-bottom: 10px; } | |
.error { color: #ff4444; } | |
</style> | |
</head> | |
<body> | |
<h1>Script Scheduler</h1> | |
<p>Next run: {{ next_run }}</p> | |
<h2>Latest Execution Logs</h2> | |
<div class="log-box"> | |
{% for log in logs|reverse %} | |
<div class="timestamp">{{ log.time }}</div> | |
{% if log.output %} | |
<div class="output">{{ log.output }}</div> | |
{% endif %} | |
{% if log.error %} | |
<div class="error">{{ log.error }}</div> | |
{% endif %} | |
<hr> | |
{% else %} | |
<div>No logs available yet</div> | |
{% endfor %} | |
</div> | |
<p><a href="/force-run">Trigger Manual Run</a></p> | |
</body> | |
</html> | |
''', next_run=next_run, logs=execution_logs) | |
def force_run(): | |
run_cli_script() | |
return "Script executed manually", 200 | |
if __name__ == '__main__': | |
app.run(host='0.0.0.0', port=7860) |