Block caching based on time I have a simple block that is used in the footer of a multiple language website. The text in the block changes based on user language so I using the following render attributes, which seems to work well.

$render['#cache'] = [ 'contexts' =&gt; ['languages'] ];


This block contains an image that is included with the following:

if( (date('Y') %2) == 1)
  $markup = '&lt;img src="/themes/THEME/images/footer_odd_year.jpg"&gt;';
else
  $markup = '&lt;img src="/themes/THEME/images/footer_even_year.jpg"&gt;';


One image is used for even numbered years and a second image is used for odd numbered years.

What is the correct way to setup caching base on this image changing once per year?

I have a similar situation with the home page of the website which changes each day.  My current plan is to clear all caching levels for the website early each morning just after mid-night.  This includes the Drupal caches, memcached and AWS Cloudfront. For pages like the home page, which change daily, I will need to keep max-age short to limit caching in the user's browser.

Is there any better way?
On this time scale, a cache TTL probably isn't the way to go, since the age is counted from creation time without respecting calendar years. You know exactly when the cache should expire (midnight on New Years') so instead of giving it a one-year maximum age it may be better to just actively clean it with a cron.

To avoid throwing away the entire cache (which can lead to significant performance degradation on some sites), you can use a cache tag: 

$render['#cache']['tags'] = ['date:year'];


And then, in the annual cron, just invalidate the date:year cache tag like this:

function custom_cron() {
  $last = \Drupal::state()-&gt;get('system.cron_last');
  if (date('Y') !== date('Y', $last)) {
    Cache::invalidateTags(['date:year']);
  }
}


(Note that this solution does the absolute minimum of cache invalidation. If you find that your site performs well even if you completely purge the cache every day, that's fine.)