【发布时间】:2021-08-11 16:43:20
【问题描述】:
我有后台 Quartz 进程每分钟发送邮件
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddQuartz(q =>
{
q.UseMicrosoftDependencyInjectionScopedJobFactory();
var jobKey = new JobKey("MailSendJob");
q.AddJob<EmailSender>(opts => opts.WithIdentity(jobKey));
q.AddTrigger(opts => opts
.ForJob(jobKey)
.WithIdentity("MailSendJob-trigger")
.WithCronSchedule("0 0/1 * * * ?"));
});
services.AddQuartzHostedService(
q => q.WaitForJobsToComplete = true);
});
当我在 main 中调用它时,它会阻止所有下一个方法,例如从未执行过的 BotOnMessage().Wait()。如何解决此问题以便在后台运行此服务而不阻塞其他方法
static void Main(string[] args)
{
while (true)
{
try
{
GetExcelFile GF = new GetExcelFile();
GF.getData();
CreateHostBuilder(args).Build().Run();
BotOnMessage().Wait(); //this method never executed
}
catch (Exception ex)
{
Console.WriteLine("Error" + ex);
}
}
}
这是我的 EmailSender 类
[DisallowConcurrentExecution]
public class EmailSender : IJob
{
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"ExcelFiles\", "testFile.xlsx");
public async Task Execute(IJobExecutionContext context)
{
using (MailMessage message = new MailMessage("sender@gmail.com", "receiver@gmail.com"))
{
message.Subject = "News";
message.Body = "test Text";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(path);
message.Attachments.Add(attachment);
using (SmtpClient client = new SmtpClient
{
EnableSsl = true,
Host = "smtp.gmail.com",
Port = 465,
Credentials = new NetworkCredential("sender@gmail.com", "testPass")
})
{
await client.SendMailAsync(message);
}
}
}
}
【问题讨论】:
-
您似乎没有触发执行任务。
-
@Batuhan 有什么建议吗?
标签: c# asp.net-core .net-core