如何在scala中定义没有var定义的Periodic更新值

时间:2016-05-19 02:30:39

标签: scala akka

我正在尝试实现没有var定义的定期更新值。

让我们说如果我有网络服务器并且必须在其中进行其他服务器的健康检查以处理用户请求。每个用户请求操作都会引用运行状况检查结果。 如果每次处理新请求时都要进行健康检查,那么成本会很高,而我想每5分钟最多更新一次健康检查结果值。

很容易如果我使用 private var result = false private var lastUpdated = 0L private val INTERVAL = 1000L * 60 * 5 def helthCheckResult = { System.currentTimeMillis() match { case currentTime if currentTime > lastUpdated + INTERVAL => result = !result // actual code should call heathcheck impl lastUpdated = currentTime result case _ => result } } 来实现这一点。

class HeathCheckActor(implicit system: ActorSystem) extends Actor {
  private var result = false
  system.scheduler.schedule(0 seconds,5 minutes,self,"update")
  def receive = {
    case "update" if sender == self =>
      result = !result // actual code should call heathcheck impl
    case "get" =>
      sender ! result
  }
}

或与Akka

var

他们正在使用var来保存结果状态。我想要实现的是在没有result的情况下实现这一点。

有没有办法做到这一点?

任何形式的信息/提示都将受到赞赏。

被修改

询问我想要实现的目标是一个不好的例子。 让我们说Boolean不是简单的状态,如Int,而是result<?php /* Template Name: Search Results */ ?> <?php get_header(); ?> <div id="content"> <header class="article-header"> <div class="row small-12 columns"> <h1 class="page-title"><?php the_title(); ?></h1> </div> </header> <!-- end article header --> <div id="inner-content" class="row"> <main id="main" class="large-8 medium-8 columns search-results" role="main"> <h2> <?php if (ICL_LANGUAGE_CODE == 'en'): ?> Search Results for: <?php elseif (ICL_LANGUAGE_CODE == 'es'): ?> Buscar resultados para: <?php endif; ?> <?php $searchResultFor = ''; if ((isset($_POST['API_Method']) && $_POST['API_Method'] != '') || (isset($_SESSION['API_Method']) && $_SESSION['API_Method'] != '')) { $_SESSION['API_Method'] = $_POST['API_Method']; $_SESSION['ZipCode'] = $_POST['ZipCode']; $methodToCall = $_POST['API_Method']; $ZipCode = $_POST['ZipCode']; $County = $_POST['County']; $State = $_POST['State']; $AddressLine1 = $_POST['AddressLine1']; $City = $_POST['City']; $StateAbbr = $_POST['StateAbbr']; $Zip = $_POST['Zip']; if ($methodToCall == 'ProviderSearchByZip') { $ZipCode = $_POST['ZipCode']; $searchResultFor = $ZipCode; } if ($methodToCall == 'ProviderSearchByCounty') { $County = $_POST['County']; $State = $_POST['State']; $searchResultFor = $County . ' ' . $State; } if ($methodToCall == 'ProviderSearchByCity') { $City = $_POST['City']; $State = $_POST['State']; $searchResultFor = $City . ' ' . $State; } if ($methodToCall == 'ProviderSearchByAddress') { $AddressLine1 = $_POST['AddressLine1']; $City = $_POST['City']; $StateAbbr = $_POST['StateAbbr']; $Zip = $_POST['Zip']; $searchResultFor = $AddressLine1 . ' ' . $City . ' ' . $StateAbbr . ' ' . $Zip; } } echo $searchResultFor; ?> </h2> <?php $methodToCall = ''; $message = ''; $objSearchData['Providers'] = array(); if (isset($_POST['API_Method']) && $_POST['API_Method'] != '') { $methodToCall = $_POST['API_Method']; $objSearchData = get_search_result($methodToCall, $ZipCode, $nameid = '', $County, $State, $City, $address1, $StateAbbr, $Zip); } ?> <?php if (!empty($objSearchData['Providers'])) { // print_R($objSearchData['Providers']['Provider']);die; if (array_key_exists(0, $objSearchData['Providers']['Provider'])) { foreach ($objSearchData['Providers']['Provider'] as $k => $fdata) { if ($k == 0) { $add1 = $fdata['AddressLine1']; $city = $fdata['City']; $state = $fdata['StateProvinceCode']; $postcode = $fdata['PostalCode']; $address = $add1 . ", " . $city . ", " . $state . ", " . $postcode; $nameid = $fdata['NameID']; $orgname = $fdata['OrganizationName']; $phone = $fdata['PhoneNumber']; $tollfree = $fdata['Toll_Free']; $fax = $fdata['FaxNumber']; $email = $fdata['EmailAddress']; $website = $fdata['WebSiteAddress']; break; } } } else { $add1 = $objSearchData['Providers']['Provider']['AddressLine1']; $city = $objSearchData['Providers']['Provider']['City']; $state = $objSearchData['Providers']['Provider']['StateProvinceCode']; $postcode = $objSearchData['Providers']['Provider']['PostalCode']; $address = $add1 . ", " . $city . ", " . $state . ", " . $postcode; $nameid = $objSearchData['Providers']['Provider']['NameID']; $orgname = $objSearchData['Providers']['Provider']['OrganizationName']; $phone = $objSearchData['Providers']['Provider']['PhoneNumber']; $tollfree = $objSearchData['Providers']['Provider']['Toll_Free']; $fax = $objSearchData['Providers']['Provider']['FaxNumber']; $email = $objSearchData['Providers']['Provider']['EmailAddress']; $website = $objSearchData['Providers']['Provider']['WebSiteAddress']; } ?> <?php $methodToCall_1 = 'GetProviderDetails'; $objSearchData_1 = get_search_result($methodToCall_1, $ZipCode, $nameid, $County, $State, $City, $address1, $StateAbbr, $Zip); ?> <div class="row search-holder"> <div class="small-12 columns"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc rutrum odio imperdiet purus pulvinar, a ultrices tellus mattis. Vestibulum nec ligula commodo, commodo ipsum sed, placerat magna. Pellentesque rutrum nulla nec iaculis volutpat. Pellentesque pellentesque sit amet ante a elementum. Nunc bibendum sodales vulputate.</p> <h3><a href="<?php echo get_permalink('262') . '?id=' . $nameid ?>"><?php echo $orgname; ?></a></h3> <div class="row"> <div class="small-12 medium-7 columns"> <p><?php echo $add1; ?><br/><?php echo $city; ?>, <?php echo $state; ?> , <?php echo $postcode; ?></p> <?php if (ICL_LANGUAGE_CODE == 'en'): ?> <p><span>Phone: </span><?php echo ($phone != '') ? $phone : "Not available"; ?></p> <?php elseif (ICL_LANGUAGE_CODE == 'es'): ?> <p><span>Teléfono: </span><?php echo ($phone != '') ? $phone : "Not available"; ?></p> <?php endif; ?> <?php if (ICL_LANGUAGE_CODE == 'en'): ?> <p> <span>Toll Free: </span><?php echo ($tollfree != '') ? $tollfree : "Not available"; ?> </p> <?php elseif (ICL_LANGUAGE_CODE == 'es'): ?> <p><span>Gratuito: </span><?php echo ($tollfree != '') ? $tollfree : "Not available"; ?> </p> <?php endif; ?> <p><span>Fax: </span><?php echo ($fax != '') ? $fax : "Not available"; ?></p> <?php if (ICL_LANGUAGE_CODE == 'en'): ?> <p> <span>Toll Free: </span><?php echo ($tollfree != '') ? $tollfree : "Not available"; ?> </p> <?php elseif (ICL_LANGUAGE_CODE == 'es'): ?> <p><span>Gratuito: </span><?php echo ($tollfree != '') ? $tollfree : "Not available"; ?> </p> <?php endif; ?> <?php if (ICL_LANGUAGE_CODE == 'en'): ?> <p><span>Email: </span><?php if ($email != "") { ?> <a href="mailto:<?php echo $email; ?>" target="_blank"><?php echo $email; ?></a> <?php } else { ?> <?php echo "Not available"; ?> <?php } ?> </p> <?php elseif (ICL_LANGUAGE_CODE == 'es'): ?> <p><span>Correo Electrónico: </span><?php if ($email != "") { ?> <a href="mailto:<?php echo $email; ?>" target="_blank"><?php echo $email; ?></a> <?php } else { ?> <?php echo "Not available"; ?> <?php } ?> </p> <?php endif; ?> <?php if (ICL_LANGUAGE_CODE == 'en'): ?> <p class="search_website"> <?php if ($website != "") { ?> <a href="http://<?php echo $website; ?>" target="_blank">Website</a> <?php } else { ?> <?php echo "Not available"; ?> <?php } ?> </p> <?php elseif (ICL_LANGUAGE_CODE == 'es'): ?> <p class="search_website"> <?php if ($website != "") { ?> <a href="http://<?php echo $website; ?>" target="_blank">Página de Internet</a> <?php } else { ?> <?php echo "Not available"; ?> <?php } ?> </p> <?php endif; ?> </div><!-- end columns --> <div class="small-12 medium-5 columns"> <?php if (ICL_LANGUAGE_CODE == 'en'): ?> <h4>Hours Of Operation</h4> <?php elseif (ICL_LANGUAGE_CODE == 'es'): ?> <h4>Horas de Operación</h4> <?php endif; ?> <?php if (!empty($objSearchData_1['Provider']['HoursOfOperation'])) { $HoursOfOperation = $objSearchData_1['Provider']['HoursOfOperation']['DayTime']; $HoursOfOperationcount = count($HoursOfOperation); for ($y = 0; $y < $HoursOfOperationcount; $y++) { $starttime24 = $HoursOfOperation[$y]['StartTime']; $starttime12 = date("g:i a", strtotime($starttime24)); $endtime24 = $HoursOfOperation[$y]['EndTime']; $endtime12 = date("g:i a", strtotime($endtime24)); echo ' <p><span>' . $HoursOfOperation[$y]['DayOfWeek'] . '</span>' . ' ' . $starttime12 . ' to ' . $endtime12 . '</p>'; } } ?> </div><!-- end columns --> </div><!-- end row --> <div class="row ccrr"> <div class="small-12 medium-9 columns"> <?php if (ICL_LANGUAGE_CODE == 'en'): ?> <h2>Access Your CCR&R's Online Child Care Search</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc rutrum odio imperdiet purus pulvinar, a ultrices tellus mattis. Vestibulum nec ligula commodo, commodo ipsum sed, placerat magna.</p> <?php elseif (ICL_LANGUAGE_CODE == 'es'): ?> <h2>Buscar el cuidado de niños en línea por su agencia local</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc rutrum odio imperdiet purus pulvinar, a ultrices tellus mattis. Vestibulum nec ligula commodo, commodo ipsum sed, placerat magna.</p> <?php endif; ?> </div><!-- end columns --> <div class="small-12 medium-3 columns"> <?php if (ICL_LANGUAGE_CODE == 'en'): ?> <a href="<?php echo $objSearchData_1['Provider']['FindChildCareNow']; ?>" class="button standard small" title="Link-State-by-State-Resources">Learn More</a> <?php elseif (ICL_LANGUAGE_CODE == 'es'): ?> <a href="<?php echo $objSearchData_1['Provider']['FindChildCareNow']; ?>" class="button standard small" title="Link-State-by-State-Resources">Aprende más</a> <?php endif; ?> </div><!-- end columns --> </div><!-- end ccrr --> </div><!-- end columns --> </div><!-- end search-holder --> <div class="row small-12 columns"> <?php if (!empty($objSearchData_1['Provider']['Counties'])) { ?> <ul class="accordion ask" data-accordion data-allow-all-closed="true"> <li class="accordion-item" data-accordion-item> <?php if (ICL_LANGUAGE_CODE == 'en'): ?> <a href="#" class="accordion-title">Areas Served</a> <?php elseif (ICL_LANGUAGE_CODE == 'es'): ?> <a href="#" class="accordion-title">Condados Servidos</a> <?php endif; ?> <div class="accordion-content" data-tab-content><?php if (strpos($objSearchData_1['Provider']['Counties'], ',')) { $exp_con = explode(',', $objSearchData_1['Provider']['Counties']); $newstring = join(', ', $exp_con); $newstring = rtrim($newstring, ","); } elseif ($objSearchData_1['Provider']['Counties'] != '') { $newstring = $objSearchData_1['Provider']['Counties']; } echo $newstring; ?> </div> </li> </ul> <?php } ?> </div><!-- end row columns --> <div class="row small-12 columns"> <ul class="accordion ask" data-accordion data-allow-all-closed="true"> <li class="accordion-item" data-accordion-item> <?php if (ICL_LANGUAGE_CODE == 'en'): ?> <a href="#" class="accordion-title">Services Offered</a> <?php elseif (ICL_LANGUAGE_CODE == 'es'): ?> <a href="#" class="accordion-title">Servicios Ofrecidos</a> <?php endif; ?> <div class="accordion-content" data-tab-content> <?php if (!empty($objSearchData_1['Provider']['Services']['Service'])) { $Service = $objSearchData_1['Provider']['Services']['Service']; echo ' <ul> '; $Servicecount = count($Service); if ($Servicecount == 1) { echo '<li>' . $Service . '</li>'; } else { for ($y = 0; $y < $Servicecount; $y++) { echo '<li>' . $Service[$y] . '</li>'; } } echo '</ul>'; } else { echo ' No services offered at this location'; } ?> </div> </li> </ul> </div><!-- end row columns --> <div class="state-links"> <?php if (ICL_LANGUAGE_CODE == 'en'): ?> <h2>State Resources</h2> <?php elseif (ICL_LANGUAGE_CODE == 'es'): ?> <h2>Recursos Estatales Útiles</h2> <?php endif; ?> <?php $stateArray = array( 'AL' => 'Alabama', 'AK' => 'Alaska', 'AZ' => 'Arizona', 'AR' => 'Arkansas', 'CA' => 'California', 'CO' => 'Colorado', 'CT' => 'Connecticut', 'DE' => 'Delaware', 'DC' => 'District of Columbia', 'FL' => 'Florida', 'GA' => 'Georgia', 'HI' => 'Hawaii', 'ID' => 'Idaho', 'IL' => 'Illinois', 'IN' => 'Indiana', 'IA' => 'Iowa', 'KS' => 'Kansas', 'KY' => 'Kentucky', 'LA' => 'Louisiana', 'ME' => 'Maine', 'MD' => 'Maryland', 'MA' => 'Massachusetts', 'MI' => 'Michigan', 'MN' => 'Minnesota', 'MS' => 'Mississippi', 'MO' => 'Missouri', 'MT' => 'Montana', 'NE' => 'Nebraska', 'NV' => 'Nevada', 'NH' => 'New Hampshire', 'NJ' => 'New Jersey', 'NM' => 'New Mexico', 'NY' => 'New York', 'NC' => 'North Carolina', 'ND' => 'North Dakota', 'OH' => 'Ohio', 'OK' => 'Oklahoma', 'OR' => 'Oregon', 'PA' => 'Pennsylvania', 'RI' => 'Rhode Island', 'SC' => 'South Carolina', 'SD' => 'South Dakota', 'TN' => 'Tennessee', 'TX' => 'Texas', 'UT' => 'Utah', 'VT' => 'Vermont', 'VA' => 'Virginia', 'WA' => 'Washington', 'WV' => 'West Virginia', 'WI' => 'Wisconsin', 'WY' => 'Wyoming' ); $args = array('post_type' => 'state', 'name' => $stateArray[$state]); $the_query = new WP_Query($args); if ($the_query->have_posts()) : while ($the_query->have_posts()) : $the_query->the_post(); if (have_rows('state_links')) : ?> <div class="row small-up-2 medium-up-3 large-up-3 state-links"> <?php while (have_rows('state_links')) : the_row(); if (have_rows('links')) : while (have_rows('links')) : the_row(); $link_title = get_sub_field('link_title'); $link_url = get_sub_field('link_url'); $link_icon = get_sub_field('link_icon'); ?> <div class="column link-content"> <div class="link-holder"> <img src="<?php echo get_bloginfo('template_directory'); ?><?= $link_icon ?>"> <a href="<?= $link_url ?>" target="_blank" class="button standard" title=""><?= $link_title ?></a> </div> </div> <?php endwhile; endif; endwhile; ?> </div> <?php endif; endwhile; endif; ?> <?php } else: { ?> <h2>No Content Avalable</h2> <?php } ?> </div><!-- end state-links --> </main><!-- end #main --> <div id="sidebar1" class="sidebar large-4 medium-4 columns" role="complementary"> <?php $sidebar = get_field('sidebar'); dynamic_sidebar('global-top'); dynamic_sidebar($sidebar); dynamic_sidebar('global-bottom'); ?> </div> </div><!-- end inner-content --> </div><!-- end content --> <?php get_footer(); ?> 可以是Int cloud表示的任何值。 换句话说,不能使用像Akka FSM这样的东西。

2 个答案:

答案 0 :(得分:3)

在这种情况下我使用Akka做的是使用(有时是滥用)here

在你的情况下

override def receive: Receive = receiveWithLastResult(false)

def receiveWithLastResult(lastResult: Boolean): Receive = {
    case "update" if sender == self =>
      context.become(receiveWithLastResult(!lastResult))
    case "get" =>
      sender ! result
  }

对于普通函数,您可以只接收先前的值,然后返回新值

  case class YourValues(result: Boolean, lastUpdated: Long)
  def helthCheckResult(previous: YourValues) = {
    System.currentTimeMillis() match {
      case currentTime if currentTime > lastUpdated + INTERVAL =>

        YourValues(result = !previous.result, lastUpdated = currentTime)

      case _ =>
        previous
    }

答案 1 :(得分:-1)

首先,重要的是要知道你为什么要这样,因为使用var来保持状态是一种绝对有效的方式,特别是对于也用于状态隔离的actor。

然后,为了避免var -or&#34;持有状态&#34;总的来说,重要的是要理解为什么要保持国家。

谁对此感兴趣?谁查询它,何时以及为什么?谁对状态变化作出反应?

那么或许简单地替换&#34;状态&#34;在观察者概念的变量中,感兴趣的部分被告知状态变化&#34;代替。