如何使用.NETCoreApp1.1实现计时器

时间:2017-01-16 10:45:49

标签: c# timer asp.net-core-1.1

在ASP.NET Core之前,我曾经实现过这样的计时器:

public class Class1
{
    Timer tm = null;

    public Class1()
    {
        this.tm.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
        this.tm.AutoReset = true;
        this.tm = new Timer(60000);
    }

    protected void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
         this.tm.Stop();

         try
         {
             // My business logic here
         }
         catch (Exception)
         {
             throw;
         }
         finally
         {
             this.tm.Start();
         }
     }
}

我对.NETCoreApp1.1控制台应用程序有同样的需求,并且 System.Timers 不再存在于ASP.NET Core中。我也尝试使用 System.Threading.Timer ,但项目不再构建。

如何使用.NETCoreApp1.1实现Timer?是否有相当于System.Timers?

1 个答案:

答案 0 :(得分:6)

好的,要使用 .NETCoreApp1.0 .NETCoreApp1.1 实现计时器,必须使用 System.Threading.Timer 。它几乎像System.Timers一样工作,你有这里的所有文档:https://msdn.microsoft.com/en-us/library/system.threading.timer(v=vs.110).aspx

如果您的项目在添加 System.Threading.Timer 包之后不再构建,那么因为您必须在Microsoft.NETCore的平台版本中添加依赖项.App到你的netcoreapp框架:

$to = $clientName;
$from = "wordpress@electronicsguide.000webhostapp.com";
$message =  $positive_email_body;

    $pdf=new FPDF('P', 'pt', array(500, 233));
    $pdf->AddFont('Georgiai', '', 'georgiai.php');
    $pdf->AddPage();
    $pdf->SetFont('georgiai', '', 16);
    $pdf->Cell(40, 10, 'This is a pdf example');
    $separator = md5(time());
    $eol = PHP_EOL;
    $filename = "invoice.pdf";
    $pdfdoc = $pdf->Output("invoice", "S");
    $attachment = chunk_split(base64_encode($pdfdoc));
    $headers = "From: ".$from.$eol;
    $headers .= "MIME-Version: 1.0".$eol;
    $headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";
    $body = "--".$separator.$eol;
    $body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
    $body .= "This is a MIME encoded message.".$eol;
    $body .= "--".$separator.$eol;
    $body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
    $body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
    $body .= $message.$eol;
    $body .= "--".$separator.$eol;
    $body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
    $body .= "Content-Transfer-Encoding: base64".$eol;
    $body .= "Content-Disposition: attachment".$eol.$eol;
    $body .= $attachment.$eol;
    $body .= "--".$separator."--";
    wp_mail( $to, $subject, $body, $headers);