【问题标题】:Return Text Status From Function从函数返回文本状态
【发布时间】:2017-08-08 08:46:06
【问题描述】:

我正在尝试创建一个可以做几件事的函数。首先,它将检查几个表以查看工作流是否已完成,然后以一种或另一种方式返回状态消息。这很容易。但是,如果 ETL 被中断,则存在一个问题,即状态表不会得到更新。因此,如果手动启动脚本,它将失败。

我想在函数中插入逻辑来检查系统时间,如果是在上午 7:00 之后,请跳过检查并运行脚本的其余部分。这就是我现在所拥有的。在我的截止时间之后它工作正常,但是当我将变量设置为小于 7 进行测试时,我没有收到任何状态消息。

run_time <- as.numeric(format(Sys.time(),"%H"));
run_time <- 4

wrkflw_check <- function(m) {
    bk <- 36
    msg <- "stoped checking"

    if (run_time > 7) {
        msg <- "Complete"
    }
    else {
      # loop until workflows complete or 3 hours. Which ever comes first
      for (i in 1:bk) {
      if ((etl_check$status == "wait") | (dl_check$status == "wait")) {
        Sys.sleep(300)
        etl_status <- paste0("etl status: ", etl_check$status)
        dl_status <- paste0(" dl status: ", dl_check$status)
        print(etl_status)
        print(dl_status)
        etl_check <- dbGetQuery(fm01, etl_sql)
        dl_check <- dbGetQuery(dl, dl_sql)
        i <- i + 1
      } else {
        i <- bk
        msg <- "Complete"
      }
    }
}}

msg <- wrkflw_check(m);

etl_check <- dbGetQuery(fm01, etl_sql)
dl_check <- dbGetQuery(dl, dl_sql)

我需要返回的是 msg 变量。

【问题讨论】:

  • (a) 你应该处理你的缩进——它会让你的代码更容易阅读。 (b) 在 R for 循环中,您不应该手动增加 i,而是使用关键字 next 进行下一次迭代。 (c) 当你想结束你的函数时,你应该使用return(msg) 来返回msg。 (d) 您可能应该将 run_time 设为函数的显式参数,而不是让您的函数在全局环境中查找它。
  • 我刚刚为您修复了缩进(始终为 2 个空格/级别)。可以更清楚地看到 if {...} else {...} 对。
  • 我插入了return语句并将run_time放入函数中,没有任何区别。

标签: r function loops time


【解决方案1】:

为了得到我想要的东西,我不得不稍微分解一下。但这现在有效。

wrkflw_check <- function(m){
    bk <- 36
    msg <- "stoped checking"
# loop until workflows complete or 3 hours. Which ever comes first
    for (i in 1:bk) {
        if ((etl_check$status == "wait") | (dl_check$status == "wait")) {
            Sys.sleep(300)
            etl_status <- paste0("etl status: ", etl_check$status)
            dl_status <- paste0(" dl status: ", dl_check$status)
            print(etl_status)
            print(dl_status)
            etl_check <- dbGetQuery(fm01, etl_sql)
            dl_check <- dbGetQuery(dl, dl_sql)
            i <- i + 1
        } else {
            i <- bk
            msg <- "Complete"
            return(msg)
        }
    }
}


run_time <- as.numeric(format(Sys.time(),"%H"));
#run_time <- 4
run_time

if (run_time > 7) {
    msg <- "Complete"
} else {
    msg <- "incomplete"
    msg <- wrkflw_check(m)
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2021-01-29
    相关资源
    最近更新 更多