Never stop learning, approaching the AI
  • 😄About
  • 🅰️AI-Candy on YouTube
    • 🎬YouTube 视频列表
    • 💠AI项目本地部署
      • 1️⃣安装 Pytorch 运行环境
      • 2️⃣在Python虚拟环境下使用 VS Code or PyCharm
        • VS Code Python format
      • 3️⃣Create python virtual environment in Linux
    • 👽AI 入门系列课程
      • 0️向量及向量运算
        • Reshape array code
      • 1️人工智能,机器学习,深度学习 和神经网络的区别
      • 2️卷积神经网络(CNN)
        • 3D CNN sample code
      • 3️Transformer 原理
      • 4️前馈神经网络 (FNN)
  • 🎭Artificial intelligence
    • 1️⃣Deep learning / machine learning
      • 👉Deep Learning Resources
      • 👉Deep learning notes
    • 2️⃣Python
      • Youtube音乐下载
      • Pytorch 安装环境配置 (old)
        • TorchEEG
      • Anaconda3 Python path
      • Data
      • IEEE-754 Floating Point Converter
        • ieee 754 conversion function
      • 文件读写
      • 文本清理
      • Python 下载在线视频
      • 修改Jupyter Notebook 默认工作目录
    • 3️⃣AI Websites
  • 🪤Programming
    • SQL
      • Delete data and reset auto-increment ID
    • Angular
      • Angular-datatables, dd/MM/yyyy, sorting (no paged list)
      • Datatables save state using localStorage
      • Variable storage method
      • Colour picker
      • Error fix for click columns on Datatable
      • Auto address use Google place
      • Auto address use Azure Maps
      • Upload file to Server
      • Validators.required OnChange input
      • Date, Time field
      • VS Code: Auto add missing imports when save
      • Datatable setting
      • Date time format
      • sticky <th> and <td> content
      • Filter booked time
      • Dropdown time selection with interval
      • Angular date online test
      • Updating data without refreshing the page
      • Object array sort and sum
      • Multi-type of columns use in one column
      • Select button for datatables
      • Switch button and event
      • Delete column from Array
      • Three-layer structure
      • Remove shadow when print mat-dialog content
      • JSON Parse && Object Array
      • Detect unused import in Typescript
      • Change location using radio button
      • display multi line message in the Toastr
      • Custom LOCALE_ID
      • Batch add data from csv to API server
        • Angular read csv and upload to Server
      • USB Port reader Web solution
      • Debug Angular app using JavaScript Debugger in VS Code
      • Skills
        • FormData & FormGroup to JSON
        • Dropdown list (customer)
        • Get current datetime
        • Get first day of year, month, and date
        • Call a function in a forEach loop
        • disable and readonly
        • Form element value
        • HTML input type
        • Input pattern (validation)
      • Display pipe (UI format)
        • Input upper case and button checked
        • Icons (Bootstrap and CoreUI)
        • Page Refresh
        • Selection list (two ways)
        • onChange Selection event
        • Random Password and Toggle
        • Password match
        • Select checkbox disable
      • Print and save to PDF
      • Import JS into Angular
      • LocalStorage
      • Angular DataTable
        • Data sort
        • A sample usage
        • Angular DataTable server side big data query
      • Change chart.js chart type
      • Angular UI - .NET API - .NET Auth
      • Angular - .NET API
      • *ngIf else && change to @if
      • Angular add reCAPTCHA v3 (Google)
      • Angular update
        • Update from v13 to v15
        • Update from v15 to v18
      • Angular application version central
      • Face detection
        • Face-api.js
      • Angular, Node version compatibility matrix
      • Clear cache
      • Angular oauth2 OIDC
      • Angular add header
    • .NET Skills
      • Add ID manually
      • Auto Mapping
        • Ignore Nesting
        • Startup setting
        • Datetime processing in AutoMapping
        • AutoMapper example
      • Validation filter
      • BaseController
      • Group by many
      • Database first, scaffold to class
      • Log setting and exception handler
      • Update appsetting.json value
      • Azure service bus message (queue)
      • Read appsetting.json value
      • Auth get user info by email
      • Azure Time zone
      • .NET API Add Service
      • Object comparison
      • Coravel Schedule
        • Read appsettings.json
      • .Net Core RDLC Report, Coravel and Email
      • Check Network and SQL server connections.
      • Datatime custom format
      • Many to Many EF
        • Many to Many CheckBox
      • PDFpig: Send Email with PDF attachment
      • .NET Core Middleware order
      • .NET API add Worker Service
      • .NET Router
      • Partial columns update
      • Add and Delete
      • 图片自适应宽度
      • ASP.NET Identity
      • Upload file to Azure
        • Upload file to Blob
      • Developer Guide
      • Code first one-many
      • ASP.NET MVC 5 Custom Error Page
      • VS can't debug
      • 通过邮编查 NSW COVID-19 感染人数
      • Jquery File Upload
      • Jquery Datepicker
      • ajax delete file from server
      • Autofac in MVC
      • Autofac in .NET Core
      • .NET Core
      • HTTP Return code
      • IdentityServer4
    • Power BI
      • Add parameter to PowerBI report
      • Convert UTC to Local time
      • Python in PowerBI
        • IEEE-754 conversion
      • PowerBI embed app - Server
      • PowerBI embed app - Client
        • Setting on portal
    • Azure service
      • Key Vault
      • Service bus - queue
      • Power Automate
      • Kusto Query Language
      • Azure Data Explorer
      • Reserved keyword on Azure Error
      • SQL Azure time convert
    • Azure blob
      • Azure blob setting
      • Display image from Blob
      • Upload image to Blob through .NET API
    • Html Bootstrap Icon, colour, size
      • Html spacing
      • Html text alignment
    • Video stream - JsMpeg
      • SSL - generate key
      • Client (SSL)
      • Websocket-Server (SSL)
      • Play RTSP video stream
    • ⏰Time Zone
      • datetime-local set date range
      • 🕐Get data by local time (UI, API)
      • 🕑Add offset hours for local UI and report
      • 🕒UTC time and Datetime convert
      • 🕓Angular - Timezone selection
      • 🕔Angular - Convert UTC to local time
      • 🕕C# Time Zone
  • >>>>>>>>>>>>>>>>>>>>>>>>>>>>
  • 🪜Apps and Skills
    • 1️Windows system app skills
      • Brother HL-2130 打印机 Toner 报警
      • VS Code 快捷键
      • Check SHA256 on windows
      • blob 视频下载
      • Photoshop 制作证件照片
      • 获取 Windows Key
      • 10进制36进制互转
      • Error when publish to Azure
      • Disable windows automatic update
      • Outlook setup for Yahoo Email
      • IIS setting
      • Windows 8/10, IIS Service
      • 安装程序出错 2052,2053 报警
      • 6 Yao Chinese UI
    • 2️Linux command
    • 3️Git command
    • 4️Bitbucket
    • 5️Gitbook Skills
    • 6️GitHub Desktop
    • 7️⃣EndNote
      • EndNote V21
      • Endnote使用技巧
      • 批量删除/修改Endnote 中 notes 栏内容
  • Android mobile connect PC
  • 💎USEFUL LINKS
    • 1️Coding websites
      • Website links
    • 2️Windows 平台工具,网站
    • 3️PotPlayer 设置
  • >>>>>>>>>>>>>>>>>>>>>>>>>>>>
  • 🚩Research >>EEG
    • 1️EEG基本知识的理论介绍
      • EEG 简介
      • EEG 的节律信号
      • EEG电极帽
      • EEG 伪迹
      • ERP 介绍
      • ERP 成分
      • EEG 数据分析软件
    • 2️LSL 应用
    • 3️EEG公开数据集汇总整理
    • 4️REDCap
      • Migration (Export & Import)
    • 5️⃣ScaneR
  • ☕Buy me a coffee
Powered by GitBook
On this page

Was this helpful?

  1. Programming
  2. .NET Skills

Coravel Schedule

https://docs.coravel.net/Installation/

// c# Add Coravel Parkage

In startup.cs add below code:

---- ConfigureServices -----
Services.AddScheduler();
Services.AddTransient<SampleInvocable>();

---- Configure ----
var provider = app.ApplicationServices;
provider.UseScheduler(scheduler =>
{
    scheduler.Schedule<SampleInvocable>();
    .EveryMinute()
    .Weekday();
});

// method 

public class SampleInvocable : IInvocable
{
    public Task Invoke()
    {
       Console.WriteLine("Every minute on weekday ..");
       return Task.CompletedTask;
     }
}
// cron expression

scheduler.Schedule(
.Cron("0 0 1 * *") // At midnight on the 1st day of each month.

0 1 * * 1 // At 01:00 AM, only on Monday
0 1 1 * * // At 01:00 AM, on day 1 of the month

scheduler.Schedule<SendDailyReportsEmailJob>()
.Cron("39 15 * * *") // run at 1:00 pm daily                 // .DailyAt(15, 29)
.Zoned(TimeZoneInfo.Local);


scheduler.Schedule<SendWeeklyReportsEmailJob>()
.Cron("0 1 * * 1")   // Cron expression - At 01:00 AM, only on Monday
.Zoned(TimeZoneInfo.Local);

scheduler.Schedule<SendMonthlyReportsEmailJob>()
.Cron("0 1 1 * *")   // Cron expression - At 01:00 AM, on day 1 of the month
.Zoned(TimeZoneInfo.Local);
               

reloadOnChange for appsettings.json

// Coravel Schudler, Change time - read value from appsettings.json

// startup.cs
public IConfiguration GetAppssetingsConfig()
{
    return new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
               .AddEnvironmentVariables()
               .Build();
}
 
public Startup(IConfiguration configuration)
{
    Configuration = configuration;
    // GetAppssetingsConfig();    ///not be sured
}
        
public IServiceProvider ConfigureServices(IServiceCollection services)
{
   // GetAppssetingsConfig();  ///not be used, not sure

    //--- schedule service
    services.AddScheduler();
    services.AddTransient<SendDailyReportsEmailJob>();
    services.AddTransient<SendWeeklyReportsEmailJob>();
    services.AddTransient<SendMonthlyReportsEmailJob>();
    ...

}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{

    // scheduler
    var provider = app.ApplicationServices;
    provider.UseScheduler(scheduler =>
    {
        // run at 1:00 AM daily     .DailyAt(1, 0)  or .Cron("0 1 * * *") 
        scheduler.Schedule<SendDailyReportsEmailJob>()
        .DailyAt(1, 0)
        .PreventOverlapping("SendDailyReportsEmailJob")
        .Zoned(TimeZoneInfo.Local);

        // Cron expression - At 01:15 AM, only on Monday
        scheduler.Schedule<SendWeeklyReportsEmailJob>()
        .Cron("15 1 * * 1")
        .Zoned(TimeZoneInfo.Local);

        // Cron expression - At 02:00 AM, on day 1 of the month
        scheduler.Schedule<SendMonthlyReportsEmailJob>()
        // .DailyAt(16, 0)
        .Cron("0 2 1 * *")
        .Zoned(TimeZoneInfo.Local);
    });

    // appsetings.json changed event
    ChangeToken.OnChange(() => this.Configuration.GetReloadToken(), () =>
    {
        using (var scope = app.ApplicationServices.CreateScope())
        {
            IScheduler scheduler = scope.ServiceProvider.GetRequiredService<IScheduler>();
            IConfiguration config = scope.ServiceProvider.GetRequiredService<IConfiguration>();

            Console.WriteLine("A new scheduled task! ...");
            // Remove your past scheduled event/task
            (scheduler as Scheduler).TryUnschedule("SendDailyReportsEmailJob");
            
            //add new task
            scheduler.Schedule<SendDailyReportsEmailJob>()
                   .Cron(config["DailyReportTime:daily-report-time"])
                   .Zoned(TimeZoneInfo.Local)
                   .PreventOverlapping("SendDailyReportsEmailJob");
        };
    });

}


//SendDailyReportsEmailJob.cs
public class SendDailyReportsEmailJob : IInvocable
{
    // run when schedule time is coming
    public async Task Invoke()
    {
         var dateString = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
         Console.WriteLine("A Email has sent!" + dateString);

         await GetDailyReport();      //  

    }

    private async Task GetDailyReport()
    {
        //sent email
    }
}

Change appsettings.json value when updating data in the database

// controller

[HttpPut]
[Route("api/setting/edit/{id}")]
public async Task<IActionResult> UpdateSetting(int id, [FromForm] SettingViewModel settingVM)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    try
    {
        var oldRecord = await _repository.GetById(id);

        if (oldRecord == null)
            return NotFound($"Couldn't find the EmailSetting id = {id}");

        var newRecord = _mapper.Map(settingVM, oldRecord);

        _repository.UpdateSetting(newRecord);

        if (await _unitOfWork.SaveAsyc() > 0)
        {
            _logger.LogInformation($"Setting id = {id} has updated !");
            string cronTime1 = getDailyCronTimeStr(newRecord.SendTime.Hour, newRecord.SendTime.Minute);      // daily-report-time1
            updateAppSetting<string>("DailyReportTime:daily-report-time1", cronTime1);

            string cronTime2 = getDailyCronTimeStr(newRecord.SendTime2?.Hour, newRecord.SendTime2?.Minute);  // daily-report-time2
            updateAppSetting<string>("DailyReportTime:daily-report-time2", cronTime2);

            return Ok(_mapper.Map<SettingViewModel>(oldRecord));
        }
        return new StatusCodeResult(StatusCodes.Status500InternalServerError);
    }
    catch (Exception ex)
    {
        _logger.LogInformation($"Exception: " + ex.Message);
    }
    return
        BadRequest($"Could not update EmailSetting id= {id}");
}
// appsettings.json
{

  "DailyReportTime": {
    "daily-report-time": "50 06 * * *",
    "daily-report-time2": "43 15 * * *"
  },
  ...
}



// EmailSetting Controller

private string getDailyCronTimeStr(int? hour, int? minute)
{
    var h = hour.ToString();
    if (h.Length == 1)
        h = "0" + h;

    var m = minute.ToString();
    if (m.Length == 1)
        m = "0" + m;

    string cronTimeStr = m + " " + h + " * * *";    // Cron("0 1 * * *") >> run at 1:00 AM daily 
    return cronTimeStr;
}

private  void updateAppSetting<T>(string key, T value)
{
   try
    {
        var path = Directory.GetCurrentDirectory();
        var filePath = Path.Combine(path, "appSettings.json");
        if (global::System.IO.File.Exists(filePath))
        {
            string json = global::System.IO.File.ReadAllText(filePath);
            dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
            var sectionPath = key.Split(":")[0];
            if (!string.IsNullOrEmpty(sectionPath))
            {
                var keyPath = key.Split(":")[1];
                var oldvalue = jsonObj[sectionPath][keyPath];

                jsonObj[sectionPath][keyPath] = value;
            }
            else
            {
                jsonObj[sectionPath] = value;  
            }

            string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
            global::System.IO.File.WriteAllText(filePath, output);
        }
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error writing app settings");
    }            
} 
PreviousObject comparisonNextRead appsettings.json

Last updated 11 months ago

Was this helpful?

Cron expression generator:

🪤
https://crontab.cronhub.io/