Windows Task Scheduler Migration Plan
Overview
This document outlines the comprehensive plan for migrating from Coravel-based task scheduling to Windows Task Scheduler for the ERP Crystal MFG application. The migration aims to improve reliability and eliminate intermittent scheduler stop issues on the Win-S IIS Server.
Current Coravel Scheduler Analysis
Scheduled Tasks (7 types):
- 001 - Indent Email Scheduler
- 002 - Invoice Email Scheduler
- 003 - Sales Order Email Scheduler
- 004 - AR Email Scheduler
- 005 - Voucher Payment Email Scheduler
- 006 - Voucher Receipt Email Scheduler
- 007 - AI Insights Scheduler
Key Components:
TaskSchedulerInitializer.cs- Dynamic scheduler configurationTaskSchedulerRepository.cs- Database operations- Individual scheduler classes implementing
IInvocable - CRON-based scheduling with database configuration
1. Flow Architecture Map
graph TD
A[Windows Task Scheduler] --> B[HTTP API Endpoints]
B --> C[Task Controllers]
C --> D[Business Logic]
D --> E[Database Operations]
E --> F[Email Services]
E --> G[Report Generation]
H[Configuration DB] --> I[Task Schedule Configuration]
I --> A
J[Monitoring] --> K[Task Execution Logs]
K --> L[Error Notifications]2. Top-Level Changes Required
ErpCrystal_MFG.Api Project:
- Remove Coravel dependencies (
Coravel,Coravel.Scheduling,Coravel.Invocable) - Remove scheduler initialization code from
Program.cs - Create new HTTP endpoints for each scheduled task
- Modify existing scheduler classes to be HTTP-callable
- Add authentication/authorization for external scheduler calls
ErpCrystal_MFG.Web Project:
- Remove Coravel references from service interfaces
- Update task scheduler UI to work with new API endpoints
- Remove any Coravel-specific UI components
ErpCrystal_MFG.Models Project:
- Update
TaskSchedulerConfigmodel to remove CRON-specific properties - Add new properties for Windows Task Scheduler configuration
3. Specific CS File Changes
New Files to Create:
3.1 ErpCrystal_MFG.Api/Controllers/ScheduledTasksController.cs
[ApiController]
[Route("api/[controller]")]
[ApiKeyAuth]
public class ScheduledTasksController : ControllerBase
{
private readonly TaskExecutionService _taskExecutionService;
[HttpPost("execute/{taskCode}")]
public async Task<IActionResult> ExecuteTask(string taskCode, [FromBody] TaskExecutionRequest request)
{
// Task execution logic
}
[HttpGet("status/{taskCode}/{dbName}")]
public async Task<IActionResult> GetTaskStatus(string taskCode, string dbName)
{
// Status retrieval logic
}
}3.2 ErpCrystal_MFG.Api/Services/TaskExecutionService.cs
public class TaskExecutionService
{
public async Task<TaskExecutionResult> ExecuteTaskAsync(string taskCode, string dbName)
{
// Centralized task execution logic
// Error handling and logging
// Status tracking
}
}3.3 ErpCrystal_MFG.Api/Models/TaskExecutionRequest.cs
public class TaskExecutionRequest
{
public string DbName { get; set; } = string.Empty;
public string TaskCode { get; set; } = string.Empty;
public string? Parameters { get; set; }
}
public class TaskExecutionResult
{
public bool Success { get; set; }
public string Message { get; set; } = string.Empty;
public DateTime ExecutionTime { get; set; }
public TimeSpan Duration { get; set; }
public Exception? Error { get; set; }
}Files to Modify:
3.4 ErpCrystal_MFG.Api/Program.cs
// Remove:
// builder.Services.AddScheduler();
// builder.Services.AddQueue();
// Remove scheduler initialization block (lines 210-215)
// Add:
builder.Services.AddScoped<TaskExecutionService>();3.5 ErpCrystal_MFG.Api/TaskScheduler/TaskSchedulerInitializer.cs
- Remove entire file or convert to configuration service
3.6 Existing Scheduler Classes (7 files)
- Modify to accept HTTP parameters instead of
IInvocablepattern - Add error handling and logging
- Remove Coravel-specific dependencies
4. Windows Task Scheduler Setup Steps
Step 1: Create Task Scheduler Jobs
- Open Task Scheduler on Win-S server
- Create New Task for each scheduled task type
- Configure Trigger based on current CRON schedules
- Set Action to call HTTP endpoint
- Configure Conditions and Settings
Step 2: HTTP Endpoint Configuration
# Example PowerShell script to create task
$action = New-ScheduledTaskAction -Execute "powershell.exe"
-Argument "-Command `"Invoke-RestMethod -Uri 'http://your-api/api/scheduledtasks/execute/001' -Method POST -Body '{dbname: 'client1'}'`""
$trigger = New-ScheduledTaskTrigger -Daily -At 9:00AM
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "IndentEmailScheduler"Step 3: Authentication Setup
- Configure API key authentication for external calls
- Set up SSL certificates for secure communication
- Configure firewall rules for API access
5. Risks and Mitigation Strategies
Risk 1: Task Execution Failures
- Mitigation: Implement comprehensive error handling and retry logic
- Monitoring: Real-time alerts for failed executions
Risk 2: Performance Impact
- Mitigation: Implement task queuing and throttling
- Monitoring: Track execution times and resource usage
Risk 3: Data Consistency
- Mitigation: Implement transaction management and rollback mechanisms
- Monitoring: Database integrity checks
Risk 4: Security Vulnerabilities
- Mitigation: Strong authentication and authorization
- Monitoring: Security audit logs
6. Migration Timeline
Phase 1: Development (2-3 weeks)
- Week 1: Create new API endpoints and modify existing schedulers
- Week 2: Implement Windows Task Scheduler integration
- Week 3: Testing and validation
Phase 2: Staging (1 week)
- Deploy to staging environment
- Test all scheduled tasks
- Performance testing
Phase 3: Production (1 week)
- Gradual migration
- Monitoring and validation
- Rollback plan preparation
7. Monitoring and Logging
Enhanced Logging:
public class TaskExecutionLogger
{
public void LogTaskStart(string taskCode, string dbName)
{
// Log task execution start
}
public void LogTaskCompletion(string taskCode, string dbName, TimeSpan duration)
{
// Log successful completion
}
public void LogTaskFailure(string taskCode, string dbName, Exception ex)
{
// Log failures and send alerts
}
}Monitoring Dashboard:
- Task execution status
- Success/failure rates
- Performance metrics
- Error alerts
8. Testing Plan
Unit Testing:
- Test individual scheduler methods
- Test error handling scenarios
- Test authentication and authorization
Integration Testing:
- Test HTTP endpoint calls
- Test Windows Task Scheduler integration
- Test database operations
Performance Testing:
- Load testing for concurrent executions
- Memory and CPU usage monitoring
- Response time validation
9. Important Considerations
Backward Compatibility:
- Maintain existing API endpoints during transition
- Gradual migration approach
- Minimal downtime
Configuration Management:
- Centralized configuration for all scheduled tasks
- Environment-specific settings
- Easy schedule modifications
Documentation:
- Complete setup documentation
- Troubleshooting guide
- Maintenance procedures
10. Detailed Implementation Steps
10.1 Phase 1: Development
Week 1: API Endpoints and Scheduler Modifications
- Create
ScheduledTasksController.cswith all required endpoints - Implement
TaskExecutionService.cswith centralized execution logic - Create request/response models
- Modify existing scheduler classes to work with HTTP calls
- Add authentication and authorization
Week 2: Windows Task Scheduler Integration
- Create PowerShell scripts for task creation
- Configure triggers for each task type
- Set up authentication and security
- Create monitoring and logging infrastructure
- Implement error handling and retry mechanisms
Week 3: Testing and Validation
- Unit testing for all new components
- Integration testing with Windows Task Scheduler
- Performance testing and optimization
- Security testing and validation
- Documentation updates
10.2 Phase 2: Staging
- Deploy to staging environment
- Test all scheduled tasks in isolation
- Test concurrent execution scenarios
- Validate performance metrics
- User acceptance testing
10.3 Phase 3: Production
- Gradual migration approach
- Monitor system performance closely
- Validate task execution results
- Implement rollback procedures
- Final documentation and training
11. Post-Migration Considerations
11.1 Monitoring and Maintenance
- Regular performance reviews
- Task execution optimization
- Security updates and patches
- User feedback collection
11.2 Continuous Improvement
- Schedule optimization based on usage patterns
- Additional monitoring features
- Enhanced error handling
- Performance tuning
11.3 Documentation Updates
- Update technical documentation
- Create user guides
- Maintenance procedures
- Troubleshooting guides
12. Success Criteria
Technical Criteria:
- All 7 scheduled tasks functioning correctly
- No data loss or corruption during migration
- Performance equal to or better than current system
- Enhanced monitoring and error handling
Business Criteria:
- Minimal business disruption during migration
- Improved reliability and uptime
- Better visibility into task execution
- Reduced maintenance overhead
13. Rollback Plan
13.1 Pre-Migration Preparation
- Backup current Coravel configuration
- Document current task schedules
- Prepare rollback scripts
- Test rollback procedures
13.2 Rollback Triggers
- Critical data corruption
- Performance degradation
- Security vulnerabilities
- Business disruption
13.3 Rollback Procedures
- Stop Windows Task Scheduler tasks
- Restore Coravel configuration
- Restart application services
- Verify data integrity
- Monitor system stability
This migration plan provides a comprehensive approach to replacing Coravel with Windows Task Scheduler while maintaining all existing functionality and improving reliability. The phased approach ensures minimal risk and allows for thorough testing at each stage.