用 Scrapy 做好的爬虫使用 Scrapyd 来管理发布启动等工作,每次手动执行也很繁琐;考虑可以使用 Hangfire 集成在 web 工程里。

Scrapyd 中启动爬虫的请求如下:

curl http://172.0.0.1:8081/schedule.json -d project=spider  -d spider=jrj_spider -u name:pwd
{"node_name": "iZbp1gf15gbzzqwvxbj18jZ", "status": "ok", "project": "spider", "spiders": 1, "version": "1492884063"}

修改:

        /// <summary>
/// 执行方法
/// </summary>
public async Task SchedulePollingBackgroundJob()
{
try
{
var response = await @"http://172.0.0.1:8081/schedule.json"
.WithBasicAuth("name", "pwd")
.PostUrlEncodedAsync(new { project = "spider", spider = "jrj_spider" })
.ReceiveString();
}
catch (Exception)
{
}
}

整个过程还是比较简单的,完整的代码:

/// <summary>
/// 配置接口
/// </summary>
public IConfigurationRoot Configuration { get; } /// <summary>
/// Redis 服务
/// </summary>
public static ConnectionMultiplexer Redis; /// <summary>
/// 构造方法
/// </summary>
/// <param name="env"></param>
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
Redis = ConnectionMultiplexer.Connect(Configuration.GetConnectionString("Redis"));
} // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//自定义的配置
services.Configure<DbSetting>(Configuration.GetSection("ConnectionStrings")); //注入 Hangfire服务
services.AddHangfire(config => config.UseRedisStorage(Redis));
// services.AddHangfire(config => config.UseSqlServerStorage("<connection string>")); //添加 cookie 中间件
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
// sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
}) //.AddAzureAdB2C(opts => Configuration.Bind("AzureAdB2C", opts))
.AddCookie(opts =>
{
opts.LoginPath = new PathString("/account/login");
opts.AccessDeniedPath = new PathString("/account/denied");
});
//返回大小写问题
services.AddMvc()
.AddJsonOptions(option => option.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver());
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
} app.UseStaticFiles(); //添加验证中间件
app.UseAuthentication(); //Hangfire
//http://docs.hangfire.io/en/latest/configuration/using-dashboard.html#configuring-authorization
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
Authorization = new[] { new HangfireDashboardAuthorizationFilter() }
});
app.UseHangfireServer();
app.UseHangfireDashboard(); //http://cron.qqe2.com
//0 0 * * MON-FRI At 00:00, Monday through Friday
//Cron.Daily(16, 30) 30 16 * * *
//30 16,17,18 * * *
//30 16,17,18 * * MON-FRI
//https://github.com/HangfireIO/Cronos
RecurringJob.AddOrUpdate(() => SchedulePollingBackgroundJob(), @"30 16,17,18 * * *", TimeZoneInfo.Local);
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Hq}/{action=Index}/{id?}");
});
}

Attention: If you are using Microsoft.Extensions.Caching.Redis package, you will need to use Hangfire.Redis.StackExchange.StrongName instead, because the former package requires StackExchange.Redis.StrongName instead of StackExchange.Redis!

REFER:

https://github.com/marcoCasamento/Hangfire.Redis.StackExchange

ASP.NET Core 中使用 Hangfire 定时启动 Scrapyd 爬虫的更多相关文章

  1. ASP.NET Core 中的应用程序启动 Startup

      ASP.NET Core 应用使用Startup类来作为启动类.   Startup类中包含了ConfigureServices方法,Configure方法,IConfiguration,IHos ...

  2. Hangfire在ASP.NET CORE中的简单实现

    hangfire是执行后台任务的利器,具体请看官网介绍:https://www.hangfire.io/ 新建一个asp.net core mvc 项目 引入nuget包 Hangfire.AspNe ...

  3. Hangfire在ASP.NET CORE中的简单实现方法

    hangfire是执行后台任务的利器,具体请看官网介绍:https://www.hangfire.io/ 新建一个asp.net core mvc 项目 引入nuget包 Hangfire.AspNe ...

  4. ASP.NET Core 中文文档 第三章 原理(1)应用程序启动

    原文:Application Startup 作者:Steve Smith 翻译:刘怡(AlexLEWIS) 校对:谢炀(kiler398).许登洋(Seay) ASP.NET Core 为你的应用程 ...

  5. [08]ASP.NET Core 中 launchsettings.json 启动配置文件

    ASP.NET Core launchsettings.json 启动配置文件 本文作者:梁桐铭- 微软最有价值专家(Microsoft MVP) 文章会随着版本进行更新,关注我获取最新版本 本文出自 ...

  6. 探索ASP.Net Core 3.0系列六:ASP.NET Core 3.0新特性启动信息中的结构化日志

    前言:在本文中,我将聊聊在ASP.NET Core 3.0中细小的变化——启动时记录消息的方式进行小的更改. 现在,ASP.NET Core不再将消息直接记录到控制台,而是正确使用了logging 基 ...

  7. Core中使用Hangfire

    之前使用Quartz.Net,后来发现hangfire对Core的继承更加的好,而且自带管理后台,这就比前者好用太多了. 安装注册 安装 PM> Install-Package Hangfire ...

  8. 在 ASP.NET Core 中执行租户服务

    在 ASP.NET Core 中执行租户服务 不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻喷,如觉得我翻译有问题请挪步原博客地址 本博文翻译自: http://gunna ...

  9. ASP.NET Core中的OWASP Top 10 十大风险-失效的访问控制与Session管理

    不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻喷,如觉得我翻译有问题请挪步原博客地址 本博文翻译自: https://dotnetcoretutorials.com/201 ...

随机推荐

  1. php 微信登录 公众号 获取用户信息 微信网页授权

    php 微信登录 公众号 获取用户信息 微信网页授权 先自己建立两个文件: index.php  和  getUserInfo.php index.php <?php //scope=snsap ...

  2. embeded_2_separate_sync

    //如果是8位的话,只选择低8位传输 //因为同步码也是可以自己设置,所以把同步码设置成parameter最好 module embeded_2_separate_sync( input clk, : ...

  3. js读取后端写入cookie出现乱码

    设置字符编码集即可 Cookie cookie = new Cookie("user",URLEncoder.encode(nMessage, "UTF-8") ...

  4. 关于Linux学习中的问题和体会

    本科期间未开展过与之相关的课程,所以初次接触Linux难免有些问题!参照老师给的学习资料中内容,逐步解决了一些问题,但还有一些问题没解决,下面列举出自己遇到的一些问题. 1.在环境变量与文件查找专题中 ...

  5. 从MS Word到Windows Live Writer

    在做笔记的时候,喜欢使用Word进行排版及插入图片,但是当将笔记发布的时候,一般的网站是不支持直接将Word中的图片进行上传的,此时使用Windows Live Writer是一个不错的选择. 可是, ...

  6. CF每日一题系列 —— 415A

    http://codeforces.com/problemset/page/7?order=BY_SOLVED_DESC 从5000以内选的,emmm还是比较水的哈 时间还是有的,所以万事万物贵在坚持 ...

  7. cocos游戏的例子(摘抄记录,非原创)

    3.1 搭建Cocos2d-JS v3.x 开发环境 下载所需的软件包 下载 Cocos Code IDE.目前 Cocos Code IDE 最新发布版本是 1.0.0-RC2.我们为什么 Coco ...

  8. pycharm的基本使用

    1.设置注释字体的颜色,如下图 2.常用快捷键 Ctrl + Space 基本的代码完成(类.方法.属性) Ctrl + Alt + Space 类名完成 Ctrl + Shift + Enter 语 ...

  9. SQL Server 字符串拼接、读取

    一.查询结果使用,字符串拼接 declare @names nvarchar(1000) declare @ParmDefinition nvarchar(1000) declare @sqltext ...

  10. [机翻] WIRER ON THE WIRE - SIGNALR协议的非正式描述

    原文 原文很简单,以下为机翻 WIRER ON THE WIRE - SIGNALR协议的非正式描述 我已经看到询问有关SignalR协议的描述的问题出现了很多.哎呀,当我开始关注SignalR时,我 ...