* Created AzureDataModel

* Created Hangfire API
This commit is contained in:
2025-02-12 20:29:10 +01:00
parent 6800781fdb
commit e7342abadd
16 changed files with 414 additions and 0 deletions

View File

@@ -0,0 +1,90 @@
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}");
}
}
}