90 lines
3.0 KiB
C#
90 lines
3.0 KiB
C#
using System.Diagnostics;
|
|
using AzureDataModel.Dtos;
|
|
using AzureDataModel.Services;
|
|
using Hangfire;
|
|
using Hangfire.Storage;
|
|
using HangfireApi.Dtos;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
namespace HangfireApi.Controllers;
|
|
|
|
[ApiController]
|
|
[Route("api/[controller]")]
|
|
public class HangfireJobsController(JobStorage jobStorage, IRecurringJobManager recurringJobManager, ITaskSchedulerService service) : ControllerBase
|
|
{
|
|
[HttpGet("GetJobsToRun")]
|
|
public async Task<ActionResult<IEnumerable<JobDto>>> GetJobsToRun()
|
|
{
|
|
IList<JobDto> jobsToRun = new List<JobDto>();
|
|
|
|
using (IStorageConnection? connection = jobStorage.GetConnection())
|
|
{
|
|
IList<RecurringJobDto>? recurringJobs = connection.GetRecurringJobs();
|
|
IList<TaskSchedulerDto>? taskSchedulers = (await service.GetTaskSchedulers()).ToList();
|
|
|
|
foreach (var recurringJob in recurringJobs)
|
|
{
|
|
TaskSchedulerDto? taskScheduler = taskSchedulers?.FirstOrDefault(ts => ts.Name == recurringJob.Id);
|
|
|
|
if (taskScheduler != null)
|
|
{
|
|
jobsToRun.Add(new JobDto(recurringJob.Id, recurringJob.Cron, taskScheduler.Path,
|
|
recurringJob.LastExecution, recurringJob.NextExecution, recurringJob.Job));
|
|
}
|
|
}
|
|
}
|
|
|
|
return Ok(jobsToRun);
|
|
}
|
|
|
|
[HttpPost("RunJobs")]
|
|
public async Task<IActionResult> RunJobs()
|
|
{
|
|
var jobsToRun = (await GetJobsToRun()).Value?.ToList();
|
|
|
|
if (jobsToRun == null || jobsToRun.Count == 0)
|
|
{
|
|
return BadRequest("Nie udało się pobrać zadań do uruchomienia.");
|
|
}
|
|
|
|
foreach (var job in jobsToRun)
|
|
{
|
|
if (!string.IsNullOrEmpty(job.Path))
|
|
{
|
|
recurringJobManager.AddOrUpdate(job.JobId, () => RunConsoleApplication(job.Path), job.Cron,
|
|
new RecurringJobOptions { TimeZone = TimeZoneInfo.Local });
|
|
}
|
|
}
|
|
|
|
return Ok("Zadania zostały zaplanowane do uruchamiania zgodnie z ich CRON.");
|
|
}
|
|
|
|
private void RunConsoleApplication(string pathToApp)
|
|
{
|
|
try
|
|
{
|
|
var process = new Process
|
|
{
|
|
StartInfo = new ProcessStartInfo
|
|
{
|
|
FileName = pathToApp,
|
|
UseShellExecute = false,
|
|
RedirectStandardOutput = true,
|
|
RedirectStandardError = true,
|
|
CreateNoWindow = true
|
|
}
|
|
};
|
|
process.Start();
|
|
string output = process.StandardOutput.ReadToEnd();
|
|
string error = process.StandardError.ReadToEnd();
|
|
process.WaitForExit();
|
|
|
|
Console.WriteLine($"Output: {output}");
|
|
Console.WriteLine($"Error: {error}");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Error executing console application: {ex.Message}");
|
|
}
|
|
}
|
|
} |