.netcore控制台->定时任务Quartz

  之前做数据同步时,用过timer、window服务,现在不用那么费事了,可以使用Quartz,并且配置灵活,使用cron表达式配置XML就可以。我用的是3.0.7版本支持.netcore。

  • 首先创建一个.netcore控制台应用程序,添加Quartz、Quartz.Jobs、Quartz.Plugins引用,这里面添加了PostgreSql数据库的连接方法,其它数据库可以做为参考,添加Npgsql、Npgsql.EntityFrameworkCore.PostgreSQL引用,目录结构如下
  • 创建数据库DBContext类
  • using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.EntityFrameworkCore;
    
    namespace QuartzPro.DbContext
    {
        public class PostgreDbContext : Microsoft.EntityFrameworkCore.DbContext
        {
            private string _conn;
            public PostgreDbContext(DbContextOptions<PostgreDbContext> options) : base(options)
            {
            }
            public PostgreDbContext(string conn)
            {
                _conn = conn;
            }
    
            protected override void OnModelCreating(ModelBuilder builder)
            {
                base.OnModelCreating(builder);
                //builder.Entity<syrequest_main>().ToTable("book", "pro");
            }
             
           // public virtual DbSet<book> book { get; set; }
    
        }
    }

     

  • 创建Job类
  • using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.Extensions.Logging;
    using Quartz;
    
    namespace QuartzPro.Jobs
    {
        public class SyncUserInfoService : IJob
        {
            private readonly ILogger<SyncUserInfoService> _logger;
    
            public SyncUserInfoService()
            {
                _logger = BootStrapIoc.GetService<ILoggerFactory>().CreateLogger<SyncUserInfoService>();
            }
            public Task Execute(IJobExecutionContext context)
            {
                _logger.LogDebug($"SyncUserInfoService Execute start...");
                return Task.Run(() =>
                {
                    using (StreamWriter sw = new StreamWriter(@"D:\print.txt", true, Encoding.UTF8))
                    {
                        sw.WriteLine(DateTime.Now + "任务执行中...");
                        sw.Close();
                    }
                });
            }
        }
    }

     

  • 创建依赖注入类
  • using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using QuartzPro.DbContext;
    
    namespace QuartzPro
    {
        public static class BootStrapIoc
        {
            /// <summary>
            /// IOC容器
            /// </summary>
            private static IServiceCollection serviceCollection { get; } = new ServiceCollection();
    
            /// <summary>
            /// 初始化IOC容器
            /// </summary>
            public static void InitIoc()
            {
    
                var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).AddEnvironmentVariables().Build();
    
                var identityConn = configuration.GetConnectionString("IdentityConnection");
                //db
                serviceCollection.AddTransient(_ => new  PostgreDbContext(identityConn));
                //log
                serviceCollection.AddLogging(configure =>
                {
                    configure.AddConfiguration(configuration.GetSection("Logging"));
                    configure.AddConsole();
                });
                //config
                serviceCollection.AddSingleton<IConfiguration>(configuration);
          
            }
    
            /// <summary>
            /// 获取实体
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <returns></returns>
            public static T GetService<T>()
            {
                return serviceCollection.BuildServiceProvider().GetService<T>();
            }
        }
    }
    

      

  • 创建任务监听XML文件
  • <?xml version="1.0" encoding="utf-8" ?>
    <job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     version="2.0">
    
      <processing-directives>
        <overwrite-existing-data>true</overwrite-existing-data>
      </processing-directives>
      <schedule>
      
        <!--同步用户信息:10分钟一次-->
        <job>
          <name>SyncUserInfoService</name>
          <group>GroupUserInfoManager</group>
          <description>同步用户信息</description>
          <job-type>QuartzPro.Jobs.SyncUserInfoService, QuartzPro</job-type>
          <durable>true</durable>
          <recover>false</recover>
        </job>
        <trigger>
          <cron>
            <name>TriggerSyncUserInfoService</name>
            <group>GroupTriggerUserInfoManager</group>
            <job-name>SyncUserInfoService</job-name>
            <job-group>GroupUserInfoManager</job-group>
            <start-time>2019-07-30T15:15:00.0Z</start-time>
            <cron-expression>0 0/10 * * * ?</cron-expression>
            <!--<cron-expression>1 0 0 * * ?</cron-expression>-->
          </cron>
        </trigger>
      </schedule>
    </job-scheduling-data>

     

  • json配置文件
  • {
      "Logging": {
        "LogLevel": {
          "Default": "Debug",
          "System": "Information",
          "Microsoft": "Information"
        },
        "Console": {
          "IncludeScopes": true
        }
      },
      "ConnectionStrings": {
        "IdentityConnection": "User ID=admin;Password=123456;Host=.;Port=5432;Database=identities;"
      }
    }

     

  • Program类,注意该项目为控制台程序 UserInfoManager.xml和 appsettings.json,需要右键设置为可输出文件

  • using System; using System.Collections.Specialized; using System.Threading.Tasks; using Quartz; using Quartz.Impl; namespace QuartzPro { class Program { private static void Main(string[] args) { BootStrapIoc.InitIoc(); var task = Run(); task.Wait(); task.ConfigureAwait(false); while (true) { Console.Read(); } } public static async Task Run() { try { var properties = new NameValueCollection { ["quartz.plugin.triggHistory.type"] = "Quartz.Plugin.History.LoggingJobHistoryPlugin, Quartz.Plugins", ["quartz.plugin.jobInitializer.type"] = "Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz.Plugins", ["quartz.plugin.jobInitializer.fileNames"] = "UserInfoManager.xml", ["quartz.plugin.jobInitializer.failOnFileNotFound"] = "true", ["quartz.plugin.jobInitializer.scanInterval"] = "120" }; ISchedulerFactory sf = new StdSchedulerFactory(properties); IScheduler scheduler = await sf.GetScheduler(); Console.WriteLine("start the schedule"); await scheduler.Start(); Console.WriteLine("end"); } catch (SchedulerException se) { await Console.Error.WriteLineAsync(se.ToString()); } catch (Exception ex) { Console.Write($"err={ex.ToString()}"); } } } } 

转载于:https://www.cnblogs.com/personblog/p/11277527.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: .NET Core 是由微软开发的跨平台版本的 .NET 框架。WS-Federation 是用于实现单点登录 (SSO) 的一种 Web 服务协议。 在 .NET Core 中实现 WS-Federation 的示例可能需要使用第三方库,如 Microsoft.AspNetCore.Authentication.WsFederation。 示例代码可能长这样: ``` using Microsoft.AspNetCore.Authentication.WsFederation; ... services.AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = WsFederationDefaults.AuthenticationScheme; }) .AddWsFederation(options => { options.MetadataAddress = "https://your-sts.com/federationmetadata/2007-06/federationmetadata.xml"; options.Wtrealm = "https://your-app.com/"; }); ``` 这个是一个概要,具体实现需要更多代码和配置以及参考文档进行查询 ### 回答2: Ws-Federation 是一种基于Web服务的信任协议,用于实现单点登录(SSO)和身份提供者和服务提供者之间的身份管理。.Net Core是微软推出的跨平台开发框架,与传统的.Net框架相比,它更加轻量级、灵活且易于扩展。 在.Net Core中实现Ws-Federation可以通过使用IdentityServer来实现。IdentityServer是一个开源的身份和访问控制服务器,它支持多种身份验证方式和协议,包括Ws-Federation。 下面以一个简单的示例来说明如何在.Net Core中使用Ws-Federation: 首先,我们需要创建一个IdentityServer的实例。可以使用IdentityServer4这个开源项目,它已经集成了Ws-Federation的支持。我们可以在项目中引入IdentityServer4包,并配置IdentityServer的选项。 然后,我们需要配置IdentityServer的客户端和身份提供者。可以在代码中配置或者使用存储来管理。 接下来,我们需要在.Net Core应用程序中添加对Ws-Federation的支持。可以使用AspNet.Security.WsFederation这个包来实现。 在应用程序中,我们需要添加一个Ws-Federation中间件,并配置它的选项,包括身份提供者的元数据地址、Realm等。 然后,我们可以在应用程序中编写需要进行身份验证的控制器和视图。 最后,我们需要启动IdentityServer和应用程序,以便能够通过浏览器访问应用程序。当用户访问应用程序时,会被重定向到身份提供者进行身份验证,验证通过后会返回一个令牌,应用程序可以使用该令牌来验证用户的身份。 总之,通过使用.Net Core和IdentityServer,我们可以很方便地实现Ws-Federation协议,实现跨平台的单点登录和身份管理。使用IdentityServer4和AspNet.Security.WsFederation这两个开源项目,我们可以更加简化和高效地开发和配置。 ### 回答3: WS-Federation 是一种用于建立信任关系的开放式标准协议,.NET Core 是微软开发的跨平台开发框架。下面以一个例子来说明如何在.NET Core 中使用 WS-Federation。 假设我们有一个公司内部的网站,需要与另外一个外部系统进行集成。外部系统使用了 WS-Federation 协议进行身份验证和授权。 首先,我们需要在我们的.NET Core 应用程序中引入相关的包,例如 Microsoft.AspNetCore.Authentication.WsFederation。 然后,我们需要配置身份验证服务,指定外部系统的元数据地址和令牌颁发方的地址。我们可以使用 AddWsFederation() 方法来配置。 接下来,我们需要编写登录和注销的控制器方法。对于登录方法,我们可以使用 Challenge() 方法来发起身份验证请求,并将外部系统的地址作为参数传递。对于注销方法,我们可以使用 SignOut() 方法来退出登录。 在网站的某个页面,我们可以添加一个按钮或者链接,当用户点击时,调用登录控制器方法,将用户重定向到外部系统的登录页面。用户在外部系统进行登录后,将被重定向回我们的网站,并返回一个包含用户信息的安全令牌。 我们可以在受保护的页面或者控制器方法中添加 [Authorize] 属性来限制只有经过身份验证的用户才能访问。当用户访问这些受保护的资源时,系统会自动使用 WS-Federation 协议来验证用户的身份,并根据授权策略决定是否允许访问。 当用户想要注销时,我们可以在页面或者控制器方法中添加一个按钮或者链接,调用注销控制器方法,将用户从当前会话中退出,并重定向至外部系统的注销页面。 通过上述步骤,我们就成功地在.NET Core 应用程序中集成了 WS-Federation 协议,实现了与外部系统的身份验证和授权。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值