Phase 10: Command Scheduler

Added comprehensive command scheduling system:

Backend:
- New scheduled_commands database table
- Scheduler processor runs every minute
- Support for three schedule types: interval, hourly, daily
- calculateNextRun() function for intelligent scheduling
- API endpoints: GET, POST, PUT (toggle), DELETE
- Executions automatically created and tracked
- Enable/disable schedules without deleting

Frontend:
- New Scheduler tab in navigation
- Create Schedule modal with worker selection
- Dynamic schedule input based on type
- Schedule list showing status, next/last run times
- Enable/Disable toggle for each schedule
- Delete schedule functionality
- Terminal-themed scheduler UI
- Integration with existing worker and execution systems

Schedule Types:
- Interval: Every X minutes (e.g., 30 for every 30 min)
- Hourly: Every X hours (e.g., 2 for every 2 hours)
- Daily: At specific time (e.g., 03:00 for 3 AM daily)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-07 23:13:27 -05:00
parent bf908568e3
commit 56f8047322
2 changed files with 412 additions and 3 deletions

View File

@@ -770,6 +770,7 @@
<button class="tab" onclick="switchTab('workflows')">📋 Workflows</button>
<button class="tab" onclick="switchTab('executions')">🚀 Executions</button>
<button class="tab" onclick="switchTab('quickcommand')">⚡ Quick Command</button>
<button class="tab" onclick="switchTab('scheduler')">⏰ Scheduler</button>
</div>
<!-- Dashboard Tab -->
@@ -903,6 +904,19 @@
<div id="quickCommandResult" style="margin-top: 20px;"></div>
</div>
</div>
<!-- Scheduler Tab -->
<div id="scheduler" class="tab-content">
<div class="card">
<h3>⏰ Scheduled Commands</h3>
<p style="color: var(--terminal-green); margin-bottom: 20px;">Automate command execution with flexible scheduling</p>
<button onclick="showCreateSchedule()">[ Create Schedule ]</button>
<button onclick="refreshData()" style="margin-left: 10px;">[ 🔄 Refresh ]</button>
<div id="scheduleList" style="margin-top: 20px;"><div class="loading">Loading...</div></div>
</div>
</div>
</div>
<!-- Create Workflow Modal -->
@@ -963,6 +977,41 @@
</div>
</div>
<!-- Create Schedule Modal -->
<div id="createScheduleModal" class="modal">
<div class="modal-content">
<h2>Create Scheduled Command</h2>
<label style="display: block; margin-bottom: 8px; font-weight: 600;">Schedule Name:</label>
<input type="text" id="scheduleName" placeholder="e.g., Daily System Check">
<label style="display: block; margin-bottom: 8px; margin-top: 15px; font-weight: 600;">Command:</label>
<textarea id="scheduleCommand" placeholder="Enter command to execute"></textarea>
<label style="display: block; margin-bottom: 8px; margin-top: 15px; font-weight: 600;">Target Workers:</label>
<div id="scheduleWorkerList" style="background: var(--bg-primary); border: 2px solid var(--terminal-green); padding: 15px; margin-bottom: 15px; max-height: 150px; overflow-y: auto;">
<div class="loading">Loading workers...</div>
</div>
<label style="display: block; margin-bottom: 8px; margin-top: 15px; font-weight: 600;">Schedule Type:</label>
<select id="scheduleType" onchange="updateScheduleInput()">
<option value="interval">Every X Minutes</option>
<option value="hourly">Every X Hours</option>
<option value="daily">Daily at Time</option>
</select>
<div id="scheduleInputContainer" style="margin-top: 15px;">
<label style="display: block; margin-bottom: 8px; font-weight: 600;">Interval (minutes):</label>
<input type="number" id="scheduleValue" placeholder="e.g., 30" min="1">
</div>
<div style="margin-top: 20px;">
<button onclick="createSchedule()">[ Create Schedule ]</button>
<button onclick="closeModal('createScheduleModal')" style="margin-left: 10px;">[ Cancel ]</button>
</div>
</div>
</div>
<script>
let currentUser = null;
let ws = null;
@@ -1097,7 +1146,7 @@
try {
const response = await fetch('/api/workflows');
const workflows = await response.json();
const html = workflows.length === 0 ?
'<div class="empty">No workflows defined yet</div>' :
workflows.map(w => `
@@ -1107,8 +1156,8 @@
<div class="timestamp">Created by ${w.created_by || 'Unknown'} on ${new Date(w.created_at).toLocaleString()}</div>
<div style="margin-top: 10px;">
<button onclick="executeWorkflow('${w.id}', '${w.name}')">▶️ Execute</button>
${currentUser && currentUser.isAdmin ?
`<button class="danger" onclick="deleteWorkflow('${w.id}', '${w.name}')">🗑️ Delete</button>`
${currentUser && currentUser.isAdmin ?
`<button class="danger" onclick="deleteWorkflow('${w.id}', '${w.name}')">🗑️ Delete</button>`
: ''}
</div>
</div>
@@ -1119,6 +1168,194 @@
}
}
async function loadSchedules() {
try {
const response = await fetch('/api/scheduled-commands');
const schedules = await response.json();
const html = schedules.length === 0 ?
'<div class="empty">No scheduled commands yet</div>' :
schedules.map(s => {
const workerIds = JSON.parse(s.worker_ids);
const workerNames = workerIds.map(id => {
const w = workers.find(worker => worker.id === id);
return w ? w.name : id.substring(0, 8);
}).join(', ');
let scheduleDesc = '';
if (s.schedule_type === 'interval') {
scheduleDesc = `Every ${s.schedule_value} minutes`;
} else if (s.schedule_type === 'hourly') {
scheduleDesc = `Every ${s.schedule_value} hour(s)`;
} else if (s.schedule_type === 'daily') {
scheduleDesc = `Daily at ${s.schedule_value}`;
}
const nextRun = s.next_run ? new Date(s.next_run).toLocaleString() : 'Not scheduled';
const lastRun = s.last_run ? new Date(s.last_run).toLocaleString() : 'Never';
return `
<div class="workflow-item" style="opacity: ${s.enabled ? 1 : 0.6};">
<div style="display: flex; justify-content: space-between; align-items: start;">
<div style="flex: 1;">
<div class="workflow-name">${s.name}</div>
<div style="color: var(--terminal-green); font-family: var(--font-mono); font-size: 0.9em; margin: 8px 0;">
Command: <code>${escapeHtml(s.command)}</code>
</div>
<div style="color: var(--terminal-amber); font-size: 0.9em; margin-bottom: 5px;">
📅 ${scheduleDesc}
</div>
<div style="color: var(--text-muted); font-size: 0.85em;">
Workers: ${workerNames}
</div>
<div class="timestamp">
Last run: ${lastRun} | Next run: ${nextRun}
</div>
</div>
<div style="margin-left: 15px;">
<span class="status ${s.enabled ? 'online' : 'offline'}" style="font-size: 0.85em;">
${s.enabled ? 'ENABLED' : 'DISABLED'}
</span>
</div>
</div>
<div style="margin-top: 10px;">
<button onclick="toggleSchedule('${s.id}')" class="small">
${s.enabled ? '⏸️ Disable' : '▶️ Enable'}
</button>
<button class="danger small" onclick="deleteSchedule('${s.id}', '${s.name}')">🗑️ Delete</button>
</div>
</div>
`;
}).join('');
document.getElementById('scheduleList').innerHTML = html;
} catch (error) {
console.error('Error loading schedules:', error);
}
}
function showCreateSchedule() {
// Populate worker checkboxes
const workerList = document.getElementById('scheduleWorkerList');
workerList.innerHTML = workers.length === 0 ?
'<div class="empty">No workers available</div>' :
workers.map(w => `
<label style="display: block; margin-bottom: 10px; cursor: pointer; padding: 8px; border: 1px solid var(--terminal-green);">
<input type="checkbox" name="scheduleWorkerCheckbox" value="${w.id}" style="width: auto; margin-right: 8px;">
<span class="status ${w.status}" style="padding: 2px 8px; font-size: 0.8em;">[${w.status === 'online' ? '●' : '○'}]</span>
<strong>${w.name}</strong>
</label>
`).join('');
document.getElementById('createScheduleModal').classList.add('show');
}
function updateScheduleInput() {
const scheduleType = document.getElementById('scheduleType').value;
const container = document.getElementById('scheduleInputContainer');
if (scheduleType === 'interval') {
container.innerHTML = `
<label style="display: block; margin-bottom: 8px; font-weight: 600;">Interval (minutes):</label>
<input type="number" id="scheduleValue" placeholder="e.g., 30" min="1">
`;
} else if (scheduleType === 'hourly') {
container.innerHTML = `
<label style="display: block; margin-bottom: 8px; font-weight: 600;">Every X Hours:</label>
<input type="number" id="scheduleValue" placeholder="e.g., 2" min="1" max="24">
`;
} else if (scheduleType === 'daily') {
container.innerHTML = `
<label style="display: block; margin-bottom: 8px; font-weight: 600;">Time (HH:MM):</label>
<input type="time" id="scheduleValue">
`;
}
}
async function createSchedule() {
const name = document.getElementById('scheduleName').value;
const command = document.getElementById('scheduleCommand').value;
const scheduleType = document.getElementById('scheduleType').value;
const scheduleValue = document.getElementById('scheduleValue').value;
const selectedWorkers = Array.from(document.querySelectorAll('input[name="scheduleWorkerCheckbox"]:checked')).map(cb => cb.value);
if (!name || !command || !scheduleValue || selectedWorkers.length === 0) {
alert('Please fill in all fields and select at least one worker');
return;
}
try {
const response = await fetch('/api/scheduled-commands', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
command,
worker_ids: selectedWorkers,
schedule_type: scheduleType,
schedule_value: scheduleValue
})
});
if (response.ok) {
closeModal('createScheduleModal');
showTerminalNotification('Schedule created successfully', 'success');
loadSchedules();
// Clear form
document.getElementById('scheduleName').value = '';
document.getElementById('scheduleCommand').value = '';
document.getElementById('scheduleValue').value = '';
} else {
const error = await response.json();
showTerminalNotification('Failed to create schedule: ' + error.error, 'error');
}
} catch (error) {
console.error('Error creating schedule:', error);
showTerminalNotification('Error creating schedule', 'error');
}
}
async function toggleSchedule(scheduleId) {
try {
const response = await fetch(`/api/scheduled-commands/${scheduleId}/toggle`, {
method: 'PUT'
});
if (response.ok) {
const data = await response.json();
showTerminalNotification(`Schedule ${data.enabled ? 'enabled' : 'disabled'}`, 'success');
loadSchedules();
} else {
showTerminalNotification('Failed to toggle schedule', 'error');
}
} catch (error) {
console.error('Error toggling schedule:', error);
showTerminalNotification('Error toggling schedule', 'error');
}
}
async function deleteSchedule(scheduleId, name) {
if (!confirm(`Delete scheduled command: ${name}?`)) return;
try {
const response = await fetch(`/api/scheduled-commands/${scheduleId}`, {
method: 'DELETE'
});
if (response.ok) {
showTerminalNotification('Schedule deleted', 'success');
loadSchedules();
} else {
showTerminalNotification('Failed to delete schedule', 'error');
}
} catch (error) {
console.error('Error deleting schedule:', error);
showTerminalNotification('Error deleting schedule', 'error');
}
}
let executionOffset = 0;
const executionLimit = 50;
@@ -2053,6 +2290,7 @@
loadWorkers();
loadWorkflows();
loadExecutions();
loadSchedules();
}
// Terminal beep sound (Web Audio API)