119 lines
4.9 KiB
C#
119 lines
4.9 KiB
C#
using Microsoft.Extensions.Logging;
|
|
using Quartz.Impl;
|
|
using Quartz;
|
|
using System.Drawing.Text;
|
|
using bdGrupoSanchoToro.db;
|
|
using System.ComponentModel.DataAnnotations.Schema;
|
|
using Microsoft.VisualBasic;
|
|
using System.Reflection;
|
|
using bdGrupoSanchoToro;
|
|
|
|
namespace ServicioGrupoSanchoToro
|
|
{
|
|
|
|
public class Worker : BackgroundService
|
|
{
|
|
private readonly ILogger<Worker> _logger;
|
|
|
|
public Worker(ILogger<Worker> logger, Configuracion Conf)
|
|
{
|
|
_logger = logger;
|
|
Procesos.Conf = Conf;
|
|
var bd = tscGrupoSanchoToro.NuevoContexto(Conf.NombreConexionBD);
|
|
var ctasgmail = bd.cuentascorreo.Where(x => x.ServidorSMTP == "smtp.gmail.com").AsEnumerable().GroupBy(x => x.Remitente).Select(x => x.FirstOrDefault()).ToList();
|
|
List<tsCorreos.TokenGmail> lt = new List<tsCorreos.TokenGmail>();
|
|
foreach (var cta in ctasgmail)
|
|
{
|
|
tsCorreos.TokenGmail tg = new tsCorreos.TokenGmail();
|
|
var Config = new GmailConfig() { ClientSecret = bd.ficherosconfiguracion.First(x => x.Codigo == cta.Remitente).Configuracion, TokenFolder = @"C:\ProgramData\Gmail\TokenGmail", Usuario = cta.Remitente, Remitente = cta.Remitente, NombreRemitente = cta.Remitente };
|
|
tg.Config = Config;
|
|
tg.id = cta.Remitente;
|
|
lt.Add(tg);
|
|
}
|
|
tsCorreos.TokenGmail.ListaTokens = lt;
|
|
}
|
|
|
|
|
|
protected override async System.Threading.Tasks.Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
string Mensaje = "Servicio GrupoSanchoToro Iniciado. Versión: " + tsUtilidades.Utilidades.ExtraeValorCadena(Assembly.GetExecutingAssembly().FullName, "Version");
|
|
try
|
|
{
|
|
bdGrupoSanchoToro.Importaciones.ImportarTodo.Importar(GeneraLogErrores);
|
|
|
|
return;
|
|
|
|
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
|
|
IScheduler scheduler = schedulerFactory.GetScheduler().Result;
|
|
scheduler.Start().Wait();
|
|
// Crear un trabajo
|
|
IJobDetail job = JobBuilder.Create<TareasProgramadas>()
|
|
.WithIdentity("TareasProgramadas", "Grupo1")
|
|
.Build();
|
|
// Crear un trigger que se ejecute diariamente a una hora específica
|
|
if (Procesos.Conf.HoraProcesosDiarios != null)
|
|
{
|
|
Mensaje += " Hora Procesos Programados: " + Procesos.Conf.HoraProcesosDiarios;
|
|
int Hora = int.Parse(Procesos.Conf.HoraProcesosDiarios.Split(":")[0]);
|
|
int Minutos = int.Parse(Procesos.Conf.HoraProcesosDiarios.Split(":")[1]);
|
|
ITrigger trigger = TriggerBuilder.Create()
|
|
.WithIdentity("MiTareaDiaria", "Grupo1")
|
|
.StartAt(DateBuilder.TodayAt(Hora, Minutos, 0))
|
|
.WithSimpleSchedule(x => x
|
|
.WithIntervalInHours(24)
|
|
.RepeatForever())
|
|
.Build();
|
|
|
|
// Programar el trabajo con el trigger
|
|
scheduler.ScheduleJob(job, trigger).Wait();
|
|
|
|
Console.WriteLine("Tarea diaria programada creada.");
|
|
}
|
|
|
|
Logs.AñadeLog(tsUtilidades.Enumeraciones.TipoLog.InicioServicio, Mensaje, Mensaje);
|
|
Comprobaciones.CompruebaReplica("replica");
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
if (_logger.IsEnabled(LogLevel.Information))
|
|
{
|
|
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
|
|
}
|
|
Procesos.Procesar();
|
|
await System.Threading.Tasks.Task.Delay(1000, stoppingToken);
|
|
}
|
|
Logs.AñadeLog(tsUtilidades.Enumeraciones.TipoLog.FinServicio, "Detención " + Mensaje, "Detención " + Mensaje);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
Logs.AñadeLog(tsUtilidades.Enumeraciones.TipoLog.FinServicio, "Detención " + Mensaje, "Detención " + Mensaje);
|
|
// When the stopping token is canceled, for example, a call made from services.msc,
|
|
// we shouldn't exit with a non-zero exit code. In other words, this is expected...
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "{Message}", ex.Message);
|
|
Environment.Exit(1);
|
|
}
|
|
|
|
}
|
|
|
|
private void GeneraLogErrores(Exception ex)
|
|
{
|
|
Logs.AñadeLog(tsUtilidades.Enumeraciones.TipoLog.Fallo, ex.Message, ex.Message);
|
|
}
|
|
}
|
|
|
|
|
|
public class TareasProgramadas : IJob
|
|
{
|
|
public Task Execute(IJobExecutionContext context)
|
|
{
|
|
Comprobaciones.CompruebaReplica();
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
|
|
|
|
|
|
}
|