如何在ASP.NET中在特定时间运行代码

3
我有一个ASP.NET MVC 5应用程序。我的应用程序的关键功能之一是上传PDF文件并通过OCR读取一些值并做其他事情。
现在我想实现一个功能,使我的应用程序在特定时间检查特定文件夹(例如pdf_folder),检查是否有PDF文件,并自动上传每个PDF文件并执行我的应用程序的其余逻辑。在上传完所有文件后,它应将所有文件移动到另一个文件夹(finished_folder)。
例如,这是我的控制器,用于处理用户手动通过我的应用程序上传PDF时上传的文件。我只想使此过程在特定时间自动化。
原始回答:The feature you are looking for is called a scheduled task or a cron job. You can create a script that checks the specific folder for PDF files and then calls the controller action that handles file upload and OCR reading. This script can be executed at specific times using the built-in Windows Task Scheduler or a Linux cron job. After uploading, you can use another script to move the uploaded files to the finished_folder.
 public ActionResult GetAlreadyScannedFileList(HttpPostedFileBase file)
    {
        string path = "";

        if (file != null && file.ContentLength > 0)
        {


                UploadFileModel uploadFileModel = new UploadFileModel();

                uploadFileModel.FileName = path;
                uploadFileModel.UserId = 1;

                //Unique guid should be generated for each and every uplaoded file.
                Guid guid;
                Session["Guid"] = guid = _uploadFileService.AddUploadFile(uploadFileModel);

                //Save chnages.
                _unitOfWork.Commit();

                UploadFileModel uploadFile = _uploadFileService.GetUploadFileByGuid(guid);
                int uploadFileId = uploadFile.UploadFileId;

                _uploadFileService.ArchiveUploadFile(uploadFile.FileName);

                //send complete mail
                _uploadFileService.SendMailAfterComplete(uploadFileId);

                return RedirectToAction("SplittedItems", "UploadFile", new { id = uploadFileId });


                return RedirectToAction("GetAlreadyScannedFileList");

    }
}

任何帮助都将不胜感激。

最初的回答。

2个回答

4
这个问题有很多解决方案。以下是我使用的2个选项:
  1. 使用Quartz.Net库创建计划任务。文档
  2. 编写控制台应用程序,并将其添加到Windows计划任务中。例如,应用程序将调用所需的方法。
  3. 对于dot net core应用程序:实现后台任务
这些方法解决了应用程序休眠的问题。

3

你需要使用后台作业来完成这个任务。

  1. 使用任务计划程序(你需要创建一个包含自己逻辑(例如你想执行的任务)的控制台应用程序,并将其添加到任务计划程序中)。
  2. 使用Hangfire (https://www.hangfire.io/)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接