【问题标题】:Run a function x amount of times then sleep for a period before going again运行一个函数 x 次,然后在再次运行之前休眠一段时间
【发布时间】:2021-05-29 22:21:18
【问题描述】:

我有一个包含 1000 个值的数据框,需要将其传递给 API。

我发现如果我传递的值超过 500 个,API 就会出现错误,所以我希望传递 400 个值,休眠 10 分钟,然后再传递 400 个值,然后再休眠 10 分钟,然后完成最后 200 个。

为了提供一个reprex,这里有一小部分数据:

examples <- data.frame(names = c(1003060377,1003213240,1003116930,1003020306,1003292350,1003094988,1003164716,1003156324,1003219981))

install.packages("pacman")

pacman::p_load(tidyverse,devtools)

devtools::install_github("frankfarach/npi")

x <- map_dfr(examples$names,npi::npi_search) %>% 
  select(addresses) %>% 
  unnest()

考虑到上面的小样本量,如果我可以在传递两个值 1 分钟后让函数进入睡眠状态,然后再继续接下来的两个等,直到所有值都被传递。

如果有人能提供帮助,我将不胜感激。

【问题讨论】:

    标签: r sleep purrr


    【解决方案1】:

    您可以使用for 循环,以便跟踪已处理的条目。

    library(dplyr)
    library(tidyr)
    
    result <- vector('list', nrow(examples))
    
    for(i in seq(nrow(examples))) {
      #Sleep for 1 minute after every 2 values
      if(i %% 2 == 0) Sys.sleep(60)
      result[[i]] <- npi::npi_search(examples$names[i])
    }
    
    bind_rows(result) %>%
      select(addresses) %>% 
      unnest(addresses)
    
    #  country_code country_name address_purpose address_type address_1
    #   <chr>        <chr>        <chr>           <chr>        <chr>    
    # 1 US           United Stat… LOCATION        DOM          6601 PHO…
    # 2 US           United Stat… MAILING         DOM          800 MARS…
    # 3 US           United Stat… LOCATION        DOM          5835 NE …
    # 4 US           United Stat… MAILING         DOM          2100 DOU…
    # 5 US           United Stat… LOCATION        DOM          1163 BLA…
    # 6 US           United Stat… MAILING         DOM          1163 BLA…
    # 7 US           United Stat… LOCATION        DOM          500 COMM…
    # 8 US           United Stat… MAILING         DOM          150 SCHA…
    # 9 US           United Stat… LOCATION        DOM          6420 CLA…
    #10 US           United Stat… MAILING         DOM          6420 CLA…
    #11 US           United Stat… LOCATION        DOM          118 W NO…
    #12 US           United Stat… MAILING         DOM          PO BOX M 
    #13 US           United Stat… LOCATION        DOM          520 S SA…
    #14 US           United Stat… MAILING         DOM          520 S SA…
    #15 US           United Stat… LOCATION        DOM          910 S. H…
    #16 US           United Stat… MAILING         DOM          24 ROY S…
    #17 US           United Stat… LOCATION        DOM          1595 HAR…
    #18 US           United Stat… MAILING         DOM          1595 HAR…
    # … with 6 more variables: address_2 <chr>, city <chr>, state <chr>,
    #   postal_code <chr>, telephone_number <chr>, fax_number <chr>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 2022-09-27
      • 1970-01-01
      相关资源
      最近更新 更多