运行.NET核心Web应用程序并同时启动进程 [英] Run .NET core web application and start process at the same time

查看:107
本文介绍了运行.NET核心Web应用程序并同时启动进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力实现一件事:运行.NET Core Web应用程序(使用kestrel)并运行将执行某些方法的Quartz.Net进程。但我所有的尝试都是不成功的。我让他们都分开工作,但我不能同时运行它们。



我的进程一直在linux服务器上运行,它必须检查用于数据库更改。我需要添加网页才能看到打印结果。所以我希望能够在网上查看这些结果(localhost:5000),同时也希望能够继续运行。



我可以做我自己做的事情试图实现? (启动Web和控制台进程并让它们在程序运行时都工作)?



我尝试过:



这是我的`Startup.cs`类:

I am trying to achieve one thing: run .NET Core web application (with kestrel) and run Quartz.Net process that would execute some methods. But all my tries have been unsuccesfull. I have them both working separately, but I can't run them at the same time.

My process is running all the time on linux server where it has to check for database changes. I needed to add web page in order to see print out results. So I want to be able to view these results on web (localhost:5000) but also for the process to keep running.

Is it possible to do what I am trying to achieve? (start web and console process AND have them both working as long as the program is running)?

What I have tried:

this is my `Startup.cs ` class:

public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton();
        services.AddLogging();
        var serviceProvider = services.BuildServiceProvider();
        services.AddMvc();
        services.AddSingleton(Configuration);
        return WindsorRegistrationHelper.CreateServiceProvider(ContainerManager.Container, services);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
        }

        app.UseStaticFiles();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

    }





这是我的Program.cs类。现在网络工作,但是这个过程没有开始。评论代码是我尝试同时运行的两种方法之一,但都失败了。





and this is my Program.cs class. Web work now, however the process is not started. The commented code is one of many ways I've tried to run both, but failed.

class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();   
    }

    public static IWebHost BuildWebHost(string[] args)
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true)
            .AddCommandLine(args)
            .Build();

        return host = new WebHostBuilder()
            .UseKestrel()
            .UseConfiguration(config)
            .UseStartup()
           .Build();
    }

    //static void Main(string[] args)
    //{
    //    var ConsOut = Console.Out; 
    //    Console.SetOut(new StreamWriter(Stream.Null));
    //    BuildWebHost(args).Start();                    
    //    Console.SetOut(ConsOut); 
    //    while (true)
    //    {
    //        RunIbit();
    //    }
    //}

    //public static IWebHost BuildWebHost(string[] args)
    //{
    //    var config = new ConfigurationBuilder()
    //        .SetBasePath(Directory.GetCurrentDirectory())
    //        .AddJsonFile("appsettings.json", optional: true)
    //        .AddCommandLine(args)
    //        .Build();

    //    var host = new WebHostBuilder()
    //        .UseKestrel()
    //        .UseConfiguration(config)
    //        .UseStartup()
    //        .UseIISIntegration()
    //       .Build();

    //    return host;
    //}

    public static void RunIbit()
    {
        IServiceCollection services = new ServiceCollection();
        Startup startup = new Startup();
        var serviceProvider = startup.ConfigureServices(services);
        IWindsorContainer container = serviceProvider.GetService();
        var configuration = container.Resolve();
        var cron = configuration[Enums.ExecutionTime];
        var _logger = container.Resolve();
        var isRunning = false;
        Execute(cron); 
        while (true)
        {
            if (!isRunning)
            {
                isRunning = true;
            }
        }
    }

    public static async void Execute(string cron)
    {
        NameValueCollection props = new NameValueCollection
        {
            { "quartz.serializer.type", "binary" }
        };
        StdSchedulerFactory factory = new StdSchedulerFactory(props);

        var sched = await factory.GetScheduler();
        await sched.Start();

        var job = JobBuilder.Create()
            .Build();

        var trigger = TriggerBuilder.Create()
            .WithCronSchedule(cron)
            .ForJob(job.Key)
            .Build();
        await sched.ScheduleJob(job, trigger);
    }
}

[PersistJobDataAfterExecution]
[DisallowConcurrentExecution]
public class Job : IJob
{
    public Task Execute(IJobExecutionContext context)
    {
        var key = context.JobDetail.Key;
        try
        {
            var t = new Task(() =>
            {
                process.MainProcess();
            });
            return Task.CompletedTask;
        }
        catch (Exception e)
        {
        }
        return null;
    }
}

推荐答案

您使用的是Quartz版本3.x吗?如果是这样,那么请看一下如何在.NET Core上运行它的简短讨论: https://stackoverflow.com/questions/41821568/how-to-start-quartz-in-asp-net-core



的想法是在调用 host.Run();
Are you using version 3.x of Quartz? If so then take a look at this short discussion on how to run it on .NET Core: https://stackoverflow.com/questions/41821568/how-to-start-quartz-in-asp-net-core

The idea is to call your method for starting the scheduler before calling host.Run();


这篇关于运行.NET核心Web应用程序并同时启动进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆