How do I write a code that starts playing animation, and stops playing it in 30 sec?
Modal timer template

Blender comes with a modal timer in its templates.  Text Editor &gt; Templates &gt; Python &gt; Operator Modal Timer Here is the timer for 2.8 converted to start playing when operator pressed, and stop after 30 seconds.

This part 

self._timer = wm.event_timer_add(1, window=context.window)


creates a 'TIMER' event every second (the 1 designates 1 second, the original has 0.1 or a tenth of a second)

When 30 of these are counted (30 seconds) the animation is stopped.

import bpy


class ModalTimerOperator(bpy.types.Operator):
    """Operator which runs its self from a timer"""
    bl_idname = "wm.modal_timer_operator"
    bl_label = "Modal Timer Operator"

    _timer = None
    count = 0

    def modal(self, context, event):
        if event.type in {'ESC'} or self.count &gt; 30:
            self.cancel(context)
            return {'CANCELLED'}

        if event.type == 'TIMER':
            self.count += 1


        return {'PASS_THROUGH'}

    def execute(self, context):
        wm = context.window_manager
        # start animating
        bpy.ops.screen.animation_play()
        self._timer = wm.event_timer_add(1, window=context.window)
        self.count = 0
        wm.modal_handler_add(self)
        return {'RUNNING_MODAL'}

    def cancel(self, context):
        bpy.ops.screen.animation_cancel(restore_frame=False)


        wm = context.window_manager
        wm.event_timer_remove(self._timer)


def register():
    bpy.utils.register_class(ModalTimerOperator)


def unregister():
    bpy.utils.unregister_class(ModalTimerOperator)


if __name__ == "__main__":
    register()

    # test call
    bpy.ops.wm.modal_timer_operator()