Azure Function计时器触发器失败,无法执行存储过程

时间:2020-07-17 06:44:43

标签: c# .net sql-server azure-functions

我想在azure函数计时器触发器上执行存储过程。 该功能已成功部署。 但是,当函数运行时,我收到此错误堆栈跟踪消息

Microsoft.Azure.WebJobs.Host.FunctionInvocationException:
...
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw:
...
Inner exception System.ComponentModel.Win32Exception handled at System.Data.SqlClient.SqlConnection.OnError:
...

这是代码,

[FunctionName("DimensionFactTableUpdate")]
public static async Task Run([TimerTrigger("%CronJobSchedule%")]TimerInfo myTimer, TraceWriter log)
{
    log.Info($"C# Timer trigger UpdateFactDimensionTable function executed at: {DateTime.Now}");
    var _connectionString = Environment.GetEnvironmentVariable("DbConnectionString");
    var _storedProcedureDimension = Environment.GetEnvironmentVariable("StoredProcedureDimension");

    if (string.IsNullOrEmpty(_connectionString) || string.IsNullOrEmpty(_storedProcedureDimension))            
        return;            

    #region UPDATE DIMENSION TABLE
    try
    {
        log.Info($"[START] Update dimension table at: {DateTime.Now}");
        using (var connection = new SqlConnection(_connectionString))
        {
            connection.Open();
            using (var command = new SqlCommand(_storedProcedureDimension, connection) { CommandType = System.Data.CommandType.StoredProcedure })
            {
                var status = await command.ExecuteNonQueryAsync();
            }
        }
        log.Info($"[END] Update Dimension table at: {DateTime.Now}");
    }
    catch(Exception ex)
    {
        log.Error(ex.ToString());
    }            
    #endregion 
}

谢谢。

======

已编辑:

这是异常消息,

System.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

1 个答案:

答案 0 :(得分:0)

因此您收到了超时异常:

这可能意味着两件事。您将无法登录到SQL Server。 Open()语句上是否发生此异常?
然后调查登录问题:

  • 您的连接字符串正确吗?
  • 是否可以从azure访问您的数据库(tcp和端口)? (如果您使用的是Azure SQL数据库,则可以)
  • 登录名是否具有正确的权限?
  • 检查SQL Server错误日志sp_readerrorlog,以详细了解登录失败的原因。

否则,如果您在ExecuteNonQueryAsync上收到异常,则表示超时。

选择1:简单的方法,但不一定是最好的

增加SqlCommand上的超时时间

command.CommandTimeout = 60; // 60 seconds = 1 Minute

选项2 :昂贵的方式

扩展您的SQL Server数据库(假设您使用的是Azure SQL)

选项3 :最耗时的方式

调查存储过程缓慢的原因,并解决此问题。 这可能有很多问题,阻塞,等待,索引差或没有索引,游标/时间等等...